Archive for the ‘Boost’ Category

Boost DateTime, Locales and Facets

Saturday, 17 October 2009

Boost DateTime extends the standard library facets for formatting dates and times according to locale.

I have had some trouble with these libraries. It seems that there is something of a flaw in the design of the standard library locales. Following are some functions that look like they work but don’t, and one that work, but looks like it shouldn’t.

(more…)

Boost: converting xtime to posix_time

Saturday, 17 October 2009

Here is some Boost code to convert (approximately) from an xtime to a posix_time. (The function forgets the nanoseconds.)

#include <boost/thread/xtime.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
::boost::posix_time::ptime
  convert_to_posix_time (const ::boost::xtime & xt) // from_xtime
{
  // this conversion is valid until
  // about the year 2038 = 1970 + 2^31 seconds
  // after which long(xt.sec) will wrap
  ::boost::posix_time::ptime pt (
      ::boost::gregorian::date (1970, boost::gregorian::Jan, 1),
      ::boost::posix_time::seconds (long (xt.sec)) );
  return pt;
}

STL Design Problem?

Thursday, 24 September 2009

Consider the following functions:

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/date_facet.hpp>
#include <clocale>

std::string format_date_crash (::boost::gregorian::date dt)
{
  std::locale locale_local ("");

  ::boost::gregorian::date_facet date_output;
  std::locale locale_adjusted (locale_local, &date_output);

  std::ostringstream date_ss;
  date_ss.imbue (locale_adjusted);

  p_date_output.format("%x");
  date_ss << dt;

  return date_ss.str();
}

std::string format_date_leakquery (::boost::gregorian::date dt)
{
  std::locale locale_local ("");

  ::boost::gregorian::date_facet * p_date_output
      = new ::boost::gregorian::date_facet;
  std::locale locale_adjusted (locale_local, p_date_output);

  std::ostringstream date_ss;
  date_ss.imbue (locale_adjusted);

  (*p_date_output).format("%x");
  date_ss << dt;

  // *** don't delete p_date_output ***
  return date_ss.str();
}

Here, I have used Boost too, but I don’t believe that the problem is in Boost.

Calls to format_date_crash() crash in the ~std::locale() destructor [oddly, I found that it crashes only on the second call].

On the other hand format_date_leakquery() looks as though it might leak: it has a new without a corresponding delete. However a test showed that it does not leak.

It seems that the std::locale constructor takes ownership of the facet, so that when the locale object is destroyed, so is the facet (ie. the facet is deleted).

Is this an instance of poor design in the STL, or is there some compelling reason that things are arranged this way?