C++0x unique_ptr 替换 scoped_ptr 取得所有权?

标签 c++ smart-pointers c++11

我以前写过这样的代码:

class P {};

class Q: public P {};

class A {
    // takes ownership
    A(P* p): p_(p) {}

    scoped_ptr<P> p_;
};

A a(new Q);

使用 C++0x,我应该将 A 类重写为:

class A {
    // takes ownership
    A(unique_ptr<P>&& p): p_(p) {}

    unique_ptr<P> p_;
};

最佳答案

我赞成 comonad 的回答,但有一点需要注意:

Whenever you want to explicitely disallow move semantics, use a scoped_ptr const unique_ptr.

我没有遇到任何 const std::unique_ptr 不如 boost::scoped_ptr 的用例。不过我愿意接受这方面的教育。

编辑:

这是 boost::scoped_ptr 的一个用例,我认为它应该会失败,但不会。 std::unique_ptr:

确实失败了
#include <iostream>

#ifdef USE_UNIQUEPTR

#include <memory>
typedef std::unique_ptr<int> P;

#else  // USE_UNIQUEPTR

#include <boost/scoped_ptr.hpp>
typedef boost::scoped_ptr<int> P;

#endif  // USE_UNIQUEPTR

int main()
{
    P p1(new int(1));
    {
        // new scope
#ifdef USE_UNIQUEPTR
        const P p2(new int(2));
#else  // USE_UNIQUEPTR
        P p2(new int(2));
#endif  // USE_UNIQUEPTR
        swap(p1, p2);  // should fail!
    }
    std::cout << *p1 << '\n';
}

如果 boost::scoped_ptr 的 promise 是它的资源不会逃出当前范围,那么它不如 const std::unique_ptr。如果我们想将 const boost::scoped_ptr 与 const::std::unique_ptr 进行比较,我不得不问:出于什么目的?它们在我看来是一样的,除了 const std::unique_ptr 允许自定义构造和销毁。

关于C++0x unique_ptr 替换 scoped_ptr 取得所有权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3019512/

相关文章:

c++ - std::sort() 中使用了哪种类型的排序?

指向 vector 时出现 C++ unordered_map 错误

c++ - 引用计数智能指针如何避免或处理引用计数器溢出?

c++ - boost::signals2 的绑定(bind)类成员函数

具有自定义比较功能的 C++ 优先级队列在 Push() 上的行为不正确

c++ - 戈朗 : call Windows DLL functions

c++ - 将公共(public)语言运行时 (/clr) .dll 链接到静态链接到 C/C++ 运行时库的静态库

c++ - 当你需要一个但只有一个引用时,创建一个假智能指针的最佳方法是什么?

c++ - 期望一个类型,得到一个模板

c++ - 具有虚拟析构函数的类的未使用 const 对象会导致段错误