我有一个函数,它使用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中没有,所以我不知何故认为对我来说是必要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"));
Run Code Online (Sandbox Code Playgroud)
但是,正如您在此处所见,我遇到了段错误.我也尝试手动delete
输入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
构造函数的文档:
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
,实施永远不会破坏这个方面.
没有回答你的问题,因为其他人已经做过了.但是,每次都不需要构建语言环境.
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)
归档时间: |
|
查看次数: |
4636 次 |
最近记录: |