谁负责删除方面?

Mar*_*cia 26 c++ locale c++11

我有一个函数,它使用Boost.DateTime库来生成当前的GMT/UTC日期和时间字符串(实例).

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();
}
Run Code Online (Sandbox Code Playgroud)

这主要基于Boost.DateTime的示例:

//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"
Run Code Online (Sandbox Code Playgroud)

我的代码工作得很好,但现在我感到不安,因为这些特殊的行包含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包装newed 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"));
Run Code Online (Sandbox Code Playgroud)

但是,正如您在此处所见,我遇到了段错误.我也尝试手动delete输入newed指针,我仍然得到相同的错误(抱歉,无法在Coliru中重现错误).

time_facet构建时,指针作为参数传递std::locale对象,所以我很困惑谁是一个负责delete荷兰国际集团的方面.

所以这是我的问题的核心:

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

请注意,这boost::posix_time::time_facet是从中boost::date_time::date_facet得出的std::locale::facet.std::locale::facet虽然我的问题是特定的,但这个问题可能会推广到time_facet.

以下是一些关于std::locale构造函数的文档:

Rap*_*ptz 28

我是否需要删除time_facet或者是负责删除它的std :: locale对象?

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

§22.3.1.6

一旦通过调用从区域设置对象获得构面引用 use_facet<>,该引用仍然可用,并且只要某个区域设置对象引用该构面,就可以缓存并重新使用其成员函数的结果.

一旦没有使用facet的所有引用,析构函数std::locale将管理和删除对facet的引用,如果它的引用计数为0.

这在C++ 11标准的§22.3.1.1.2中都有说明.它声明:

构造函数的refs参数用于生命周期管理.

- For refs == 0,delete static_cast<locale::facet*>(f)当包含facet的最后一个locale对象被销毁时,实现执行(其中f是指向facet的指针); 因为 refs == 1,实施永远不会破坏这个方面.


Jag*_*ath 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();
}
Run Code Online (Sandbox Code Playgroud)