我以前写过这样的代码:
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_ptrconst 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/