56

在 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.
}

编辑:现在,我正在使用这个黑客,这似乎是我目前能得到的最好的......

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.
}
4

5 回答 5

71

unique_ptr如果没有 C++0x(它是标准库的一部分,因此 Boost 不需要提供它),就不可能创建类似的东西。

特别是没有右值引用,这是 C++0x 中的一个特性,unique_ptr无论有没有 Boost,一个健壮的实现都是不可能的。

在 C++03 中,有一些可能的替代方案,尽管每个都有其缺陷。

  • boost::shared_ptr就功能而言,这可能是最简单的替代品。您可以在任何您使用 a 的地方安全地使用它,unique_ptr并且它会起作用。由于增加了引用计数,它不会那么有效。但是,如果您正在寻找能够处理所有事情的简单替代品,unique_ptr那么这可能是您最好的选择。(当然,ashared_ptr也可以做更多事情,但它也可以简单地用作 . 的替代品unique_ptr。)
  • boost::scoped_ptr类似于unique_ptr但不允许转让所有权。只要智能指针在其生命周期内保持独占所有权,它就可以很好地工作。
  • std::auto_ptr工作方式与 非常相似unique_ptr,但有一些限制,主要是它不能存储在标准库容器中。如果您只是在寻找一个允许所有权转移的指针,但它并不意味着存储在容器中或复制,那么这可能是一个不错的选择。
于 2010-06-01T22:36:51.853 回答
38

Boost 1.57开始, Boost.Move库中有一个官方unique_ptr实现。

文档中:

(...) 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);
}

请参阅Wandbox 上的实时示例。请注意,代码在 C++98 模式 (!) 下使用 gcc 4.6.4 编译得很好。

boost::movelib::unique_ptr当应用于基类/派生类的案例时,有趣的是,该实现为基类中虚拟析构函数的声明提供了编译时检查。如果您碰巧省略了它,代码将无法编译(单击“运行(...)”按钮以查看编译器错误消息)。

一个小问题是包含来自boost/move目录,但代码位于boost::movelib命名空间中(细微差别但可能很烦人)。

有关更多详细信息,另请参阅boost 邮件列表上的线程。

感谢 Ion Gaztañaga 提供了这段绝对独特且有用的代码。

于 2015-01-28T13:05:51.177 回答
10

您可能想尝试 Howard Hinnant 的unique_ptr<>C++03 的“概念证明”实现(免责声明 - 我没有):

他的一个例子是返回一个unique_ptr<int>

unique_ptr<int> factory(int i)
{
    return unique_ptr<int>(new int(i));
}
于 2010-06-01T22:56:01.573 回答
5

unique_ptr进程间库怎么样?

于 2010-06-01T21:39:09.037 回答
4

我用过 Howard Hinnant 的unique_ptr。如果您不擅长从编译器中读取疯狂的元编程错误,您可能需要避开。然而,在 90% 的情况下,它的行为就像一个 unique_ptr。

否则,我建议传递参数 asboost::scoped_ptr&并在内部交换以窃取所有权。要获得 unique_ptr 样式的返回值,请使用auto_ptr. 捕获 a 中的auto_ptr返回值,shared_ptr避免scoped_ptr直接使用auto_ptr

于 2010-06-02T15:20:37.043 回答