STL Design Problem?

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?

Advertisements

One Response to “STL Design Problem?”

  1. Greg Rubino Says:

    I’ve just observed this phenomenon myself… very disappointing. I wonder if this is documented anywhere else? I’m going to sniff around the stl and other forums about this. I can’t imagine that this is a necessary evil, but I’ve been wrong before.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: