2013-07-22 111 views
23

我有一个函数使用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的,所以我莫名其妙地推测,当务之急是为我deletedate_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这个方面。

因此,这里是我的问题的核心:

  • 我必须对deletetime_facet或者是std::locale对象负责delete荷兰国际集团呢?

请注意,boost::posix_time::time_facetboost::date_time::date_facet这,反过来,从std::locale::facet得出的。这个问题可能概括为std::locale::facet,虽然我的问题是特定于time_facet

这里是std::locale的构造一些文档:

回答

24

我需要删除time_facet还是std :: locale对象 负责删除它吗?

你不需要从std::locale::facet删除time_facet只要time_facet派生,它应该。 std::locale::facet是一个基类,所有方面都应该从实现一种引用计数的形式中派生出来。标准这样说:

§22.3.1.6

一旦小面参考是从一个区域设置对象通过调用 use_facet<>得到,该参考文献仍然可用,并且从它 成员函数的结果可以是缓存和重用,只要某些 区域设置对象引用该方面。

一旦方面的所有引用不被使用,如果它的引用计数为0

这在§22.3.1.1所有指定的std::locale的析构函数将管理和删除的小引用。 2在C++ 11标准中。它的地址如下:

构造函数的refs参数用于生存期管理。

- 对于refs == 0,实施执行delete static_cast<locale::facet*>(f)(其中,f是一个指针刻面) 当包含小面的最后的区域设置对象被销毁;对于 refs == 1,实现从不破坏方面。

2

的语言环境是负责删除方面。

+0

这意味着locale不能被声明为'const static'吗? – agodinhost

5

不回答你的问题,因为其他人已经做到了。但是,实际上并不需要每次构建语言环境。

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(); 
}