我有一个函数使用Boost.DateTime库来生成当前的GMT/UTC日期和时间字符串(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();
}
这主要是基于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"
我的代码工作很好,但我现在因为含有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"));
正如你所看到的,有中没有delete
Boost.DateTime的,所以我莫名其妙地推测,当务之急是为我delete
的date_facet
。我用std::unique_ptr
来包装new
ed time_facet
对象。
std::unique_ptr<boost::posix_time::time_facet> facet(new boost::posix_time::time_facet("%a, %d %b %Y %H:%M:%S GMT"));
但是,我得到段错误,您可以在here中看到。我也试过手动编辑new
ed指针,并且仍然得到相同的错误(抱歉,无法在Coliru中重现错误)。
time_facet
指针在构造std::locale
对象时作为参数传递,所以我很困惑谁负责delete
这个方面。
因此,这里是我的问题的核心:
- 我必须对
delete
的time_facet
或者是std::locale
对象负责delete
荷兰国际集团呢?
请注意,boost::posix_time::time_facet
从boost::date_time::date_facet
这,反过来,从std::locale::facet
得出的。这个问题可能概括为std::locale::facet
,虽然我的问题是特定于time_facet
。
这里是std::locale
的构造一些文档:
这意味着locale不能被声明为'const static'吗? – agodinhost