c++ - unique_ptr boost 等效?

标签 c++ boost c++11 unique-ptr

在 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++0x(它是标准库的一部分,因此 Boost 不需要提供它),就不可能创建像 unique_ptr 这样的东西。

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

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

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

关于c++ - unique_ptr boost 等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2953530/

相关文章:

c++程序在字符数组中插入单词

c++ - 静态局部变量什么时候出现?

c++ - 使用 Boost Spirit 解析带有数组的结构

c++ - 使相同的 C++ 类型别名不兼容

c++ - 为使用函数对象而编写的类也可以使用 lambda 或 std::function 类型吗?

C++ 时间() 函数

c++ - boost lambda 示例

c++ - 我如何扩展 boost spirit 语法

c++ - 将 boost::lockfree 与 c++11 线程支持库一起使用是否安全?

c++ - Netbeans 无法解析符号 c++11