unique_ptr提升等价?

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,但有一些限制,主要是它不能存储在标准库容器中.如果您只是寻找一个允许转让所有权的指针,但这并不意味着存储在容器中或复制,这可能是一个不错的选择.

  • 'auto_ptr`的+1 - 因为`unique_ptr`不会在[auto_ptr导致错误的地方]编译(http://stackoverflow.com/questions/111478/why-is-it-wrong-to-use-stdauto- ptr-with-stl-containers),这正是OP正在寻找的. (4认同)
  • 考虑到r值refs不存在,Howard Hinnant的c ++ 03 unique_ptr运行良好. (4认同)
  • boost :: scoped_ptr是一个不好的选择,因为它不适用于正向声明的类。boost :: shared_ptr是一个不好的选择,因为它有大量的开销。 (2认同)
  • `boost :: scoped_ptr`的另一个缺点是它不提供客户删除器. (2认同)
  • 截至目前,此答案不再无效。请参阅 [我的回答](http://stackoverflow.com/a/28193068/1776942),其中描述了 Boost 1.57 中引入的 `boost::movelib::unique_ptr`。 (2认同)

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)


fbr*_*eto 5

如何unique_ptr图书馆吗?

  • Interprocess unique_ptr有自己的C++ 03移动仿真,如果我没错,那就和Boost.Move一样. (7认同)