C ++ 0x unique_ptr会取代scoped_ptr取得所有权? [英] C++0x unique_ptr replaces scoped_ptr taking ownership?
问题描述
我曾经写过这样的代码:
class P {};
class Q:public P {};
class A {
//取得所有权
A(P * p):p_(p){}
scoped_ptr& p_;
};
A a(new Q);
对于C ++ 0x,我应该将A类重写为:
class A {
//取得所有权
A(unique_ptr< P&& p):p_(p){}
unique_ptr< P> p_;
};
我已经注意到comonad的回答, :
每当你想要明确
不允许 请使用scoped_ptrconst unique_ptr 。
其中 const std :: unique_ptr
低于 boost :: scoped_ptr
的情况。
下面是一个使用案例:
code> boost :: scoped_ptr ,我认为应该失败,但不是。它不会为<$ c $ c> 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); //应该失败!
}
std :: cout<< * p1<< '\\\
';
}
如果 boost :: scoped_ptr
是它的资源不会逃避当前范围,那么它不如把一个
const std :: unique_ptr
那样承诺。如果我们想比较const boost :: scoped_ptr到const :: std :: unique_ptr,我要问:为什么目的?它们对我来说是一样的,除了一个const std :: unique_ptr允许自定义的构造和销毁。
I used to write code like this:
class P {};
class Q: public P {};
class A {
// takes ownership
A(P* p): p_(p) {}
scoped_ptr<P> p_;
};
A a(new Q);
With C++0x, should I rewrite class A as:
class A {
// takes ownership
A(unique_ptr<P>&& p): p_(p) {}
unique_ptr<P> p_;
};
I've upvoted comonad's answer, but with a caveat:
Whenever you want to explicitely disallow move semantics, use a
scoped_ptrconst unique_ptr.
I have not come across any use cases where a const std::unique_ptr
is inferior to a boost::scoped_ptr
. However I'm open to education on the subject.
Edit:
Here is a use case of boost::scoped_ptr
that I think should fail, but does not. It does fail for 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';
}
If the promise of boost::scoped_ptr
is that its resource will not escape the current scope, then it is not as good at holding that promise as a const std::unique_ptr
. If we want to compare const boost::scoped_ptr to const::std::unique_ptr, I have to ask: for what purpose? They seem the same to me, except that a const std::unique_ptr allows customized construction and destruction.
这篇关于C ++ 0x unique_ptr会取代scoped_ptr取得所有权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!