Cla*_*bel 55 c++ boost unique-ptr c++11
在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.
}
Run Code Online (Sandbox Code Playgroud)
编辑:现在,我正在使用这个黑客,这似乎是我能在这一点上得到的最好的......
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.
}
Run Code Online (Sandbox Code Playgroud)
jal*_*alf 68
不可能创建像unique_ptr
没有C++ 0x的东西(它是标准库的一部分,因此Boost不需要提供它).
特别是没有rvalue引用(这是C++ 0x中的一个特性)unique_ptr
,无论有没有Boost ,都不可能实现强大的实现.
在C++ 03中,有一些可能的替代方案,尽管每个都有它们的缺陷.
boost::shared_ptr
在能力方面可能是最简单的替代品.您可以安全地在任何您使用它的地方使用它unique_ptr
并且它可以工作.由于添加了引用计数,它不会那么高效.但如果你正在寻找能够处理所有事情的简单替代品unique_ptr
,这可能是你最好的选择.(当然,a shared_ptr
也可以做得更多,但它也可以简单地用作替代品unique_ptr
.)boost::scoped_ptr
类似unique_ptr
但不允许转让所有权.只要智能指针在其整个生命周期中保留独占所有权,它就能很好地工作.std::auto_ptr
工作非常相似unique_ptr
,但有一些限制,主要是它不能存储在标准库容器中.如果您只是寻找一个允许转让所有权的指针,但这并不意味着存储在容器中或复制,这可能是一个不错的选择.Ada*_*nek 35
从Boost 1.57开始unique_ptr
,Boost.Move库中有一个官方实现.
从文档:
(...)std :: unique_ptr的替代品,也可以从C++ 03编译器中使用.
代码在<boost/move/unique_ptr.hpp>
头文件中可用,并且位于boost::movelib
命名空间中.而且,Boost.Move库提供了make_unique()
工厂函数<boost/move/make_unique.hpp>
,也在boost::movelib
命名空间中.
因此,问题的例子可以这样实现:
#include <boost/move/unique_ptr.hpp>
using boost::movelib::unique_ptr;
unique_ptr<Base> create_base()
{
return unique_ptr<Base>(new Derived);
}
Run Code Online (Sandbox Code Playgroud)
查看Wandbox上的实例.请注意,代码在C++ 98模式(!)中使用gcc 4.6.4编译得很好.
是什么在有趣的boost::movelib::unique_ptr
,当应用到你的情况与基地/派生类的实现提供了在基类虚析构函数的声明编译时检查.如果您碰巧省略它,代码将无法编译(单击"运行(...)"按钮以查看编译器错误消息).
一个小问题是包括来自boost/move
目录但代码存在于boost::movelib
命名空间中(细微差别但可能很烦人).
有关更多详细信息,另请参阅boost邮件列表中的线程.
感谢IonGaztañaga这个绝对独特且有用的代码.
Mic*_*urr 10
您可能想尝试Howard Hinnant的unique_ptr<>
C++ 03 "概念证明" 实现(免责声明 - 我没有):
他的一个例子是返回unique_ptr<int>
:
unique_ptr<int> factory(int i)
{
return unique_ptr<int>(new int(i));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36726 次 |
最近记录: |