1

I have the next code:

 boost::posix_time::time_facet facet("%Y-%m-%dT%H:%M:%f");
 std::stringstream ss;
 ss.imbue(std::locale(ss.getloc(), &facet));

And when I run the this code it looks like compiler try to free the facet during ss destructor call (debuger says it).

When I run this code:

 std::stringstream ss;
 ss.imbue(std::locale(ss.getloc(), new boost::posix_time::time_facet("%Y-%m-%dT%H:%M:%f")));

all right.

So, I wonder if exists any documentation about this behavior or reason why local takes ownership. I've tried to find out the explanation but there is nothing in the documentation.

Does std::locale() take ownership of time_facet?

voltento
  • 833
  • 10
  • 26
  • Possible duplicate of [Who is responsible for deleting the facet?](https://stackoverflow.com/questions/17779660/who-is-responsible-for-deleting-the-facet) – Jodocus May 07 '18 at 17:01

1 Answers1

2

http://en.cppreference.com/w/cpp/locale/locale/locale

template< class Facet > locale( const locale& other, Facet* f ); (7)

Overload 7 is typically called with its second argument, f, obtained directly from a new-expression: the locale is responsible for calling the matching delete from its own destructor.

There is also another hint about this in http://eel.is/c++draft/locale.facet#3:

The refs argument to the constructor is used for lifetime management. For refs == 0, the implementation performs delete static_­cast(f) (where f is a pointer to the facet) when the last locale object containing the facet is destroyed; for refs == 1, the implementation never destroys the facet.

It follows that there is an internal refcounting mechanism in facet (and derived classes). This more or less implies that the facet you pass to locale is shared with it and, if you do not explicitly increase its reference count, will be destroyed with it, since passing a pointer to it cannot increase the refcount.

Max Langhof
  • 23,383
  • 5
  • 39
  • 72