【发布时间】:2011-02-26 13:36:51
【问题描述】:
在 boost 库中是否有 C++1x 的 std::unique_ptr 的等效类?我正在寻找的行为是能够拥有一个异常安全的工厂函数,就像这样......
std::unique_ptr<Base> create_base()
{
return std::unique_ptr<Base>(new Derived);
}
void some_other_function()
{
std::unique_ptr<Base> b = create_base();
// Do some stuff with b that may or may not throw an exception...
// Now b is destructed automagically.
}
编辑:现在,我正在使用这个 hack,这似乎是目前我能得到的最好的......
Base* create_base()
{
return new Derived;
}
void some_other_function()
{
boost::scoped_ptr<Base> b = create_base();
// Do some stuff with b that may or may not throw an exception...
// Now b is deleted automagically.
}
【问题讨论】:
-
另外,是否可以通过让复制构造函数具有移动语义,然后析构函数在释放前检查来创建这种效果?
标签: c++ boost c++11 unique-ptr