I have a function that uses the Boost.DateTime library for generating the current GMT/UTC date and time string (live example).
std::string get_curr_date() {
auto date = boost::date_time::second_clock<boost::posix_time::ptime>::universal_time();
boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%a, %d %b %Y %H:%M:%S GMT");
std::ostringstream os;
os.imbue(std::locale(os.getloc(), facet));
os << date;
return os.str();
}
This is mostly based on Boost.DateTime's example:
//example to customize output to be "LongWeekday LongMonthname day, year"
// "%A %b %d, %Y"
date d(2005,Jun,25);
date_facet* facet(new date_facet("%A %B %d, %Y"));
std::cout.imbue(std::locale(std::cout.getloc(), facet));
std::cout << d << std::endl;
// "Saturday June 25, 2005"
My code worked nicely, but now I'm feeling uneasy because of these particular lines containing new
:
boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%a, %d %b %Y %H:%M:%S GMT");
date_facet* facet(new date_facet("%A %B %d, %Y"));
As you can see, there is no delete
in Boost.DateTime's so I somehow presumed that it is imperative for me to delete
the date_facet
. I used std::unique_ptr
to wrap the new
ed time_facet
object.
std::unique_ptr<boost::posix_time::time_facet> facet(new boost::posix_time::time_facet("%a, %d %b %Y %H:%M:%S GMT"));
However, I am getting segfault errors, as you can see in here. I have also tried manually delete
ing the new
ed pointer, and am still getting the same errors (sorry, can't reproduce error in Coliru).
The time_facet
pointer is passed as an argument when constructing an std::locale
object, so I'm confused who's the one responsible for delete
ing the facet.
So here is the core of my question:
- Am I required to
delete
thetime_facet
or is thestd::locale
object responsible fordelete
ing it?
Please note that boost::posix_time::time_facet
is derived from boost::date_time::date_facet
which is, in turn, derived from std::locale::facet
. This question might generalized to std::locale::facet
, though my problem is specific to time_facet
.
Here are some docs on std::locale
's constructors:
- MSDN
- cppreference.com