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() {
Am I required to delete the time_facet or is the std::locale object responsible for deleteing the it?
You're not required to delete the time_facet
so long as time_facet
derives from std::locale::facet
, which it should. The std::locale::facet
is a base class that all facets should derive from that implement a form of reference counting. The standard says this:
§ 22.3.1.6
Once a facet reference is obtained from a locale object by calling
use_facet<>
, that reference remains usable, and the results from member functions of it may be cached and re-used, as long as some locale object refers to that facet.
Once all references of the facet are not being used, the destructor of std::locale
will manage and delete references to the facet if its ref count is 0.
This is all specified in §22.3.1.1.2 in the C++11 standard. Where it states:
The refs argument to the constructor is used for lifetime management.
— For
refs == 0
, the implementation performsdelete static_cast<locale::facet*>(f)
(where f is a pointer to the facet) when the last locale object containing the facet is destroyed; forrefs == 1
, the implementation never destroys the facet.
The locale is responsible for deleting the facet.
Not answering your question as others have already done it. But, it's really not required to construct the locale everytime.
std::string get_curr_date_time() {
namespace bpt = boost::posix_time;
namespace bdt = boost::date_time;
std::ostringstream os;
auto date = bdt::second_clock<bpt::ptime>::universal_time();
const static std::locale currlocale (os.getloc(), new bpt::time_facet("%Y%m%d%H%M%S"));
boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%a, %d %b %Y %H:%M:%S GMT");
os.imbue(currlocale);
os << date;
return os.str();
}