如何为具有unique_ptr
成员变量的类实现复制构造函数?我只是在考虑C++11。
发布于 2013-04-16 14:24:20
由于unique_ptr
不能共享,因此您需要深度复制其内容或将unique_ptr
转换为shared_ptr
。
class A
{
std::unique_ptr< int > up_;
public:
A( int i ) : up_( new int( i ) ) {}
A( const A& a ) : up_( new int( *a.up_ ) ) {}
};
int main()
{
A a( 42 );
A b = a;
}
正如NPE提到的,你可以使用移动函数而不是复制函数,但这会导致你的类的语义不同。移动函数需要使成员显式地通过std::move
可移动。
A( A&& a ) : up_( std::move( a.up_ ) ) {}
拥有一套完整的必要运算符也会导致
A& operator=( const A& a )
{
up_.reset( new int( *a.up_ ) );
return *this,
}
A& operator=( A&& a )
{
up_ = std::move( a.up_ );
return *this,
}
如果你想在std::vector
中使用你的类,你基本上必须决定向量是否应该是对象的唯一所有者,在这种情况下,它足以使类可移动,但不能复制。如果您省略了copy-ctor和copy-assignment,编译器将指导您如何将std::vector与仅移动类型一起使用。
发布于 2014-11-24 19:50:41
尝试使用此帮助器创建深层副本,并在源unique_ptr为空时进行处理。
template< class T >
std::unique_ptr<T> copy_unique(const std::unique_ptr<T>& source)
{
return source ? std::make_unique<T>(*source) : nullptr;
}
例如:
class My
{
My( const My& rhs )
: member( copy_unique(rhs.member) )
{
}
// ... other methods
private:
std::unique_ptr<SomeType> member;
};
发布于 2013-04-16 14:32:34
丹尼尔·弗雷提到了拷贝解决方案,我想谈谈如何移动unique_ptr
#include <memory>
class A
{
public:
A() : a_(new int(33)) {}
A(A &&data) : a_(std::move(data.a_))
{
}
A& operator=(A &&data)
{
a_ = std::move(data.a_);
return *this;
}
private:
std::unique_ptr<int> a_;
};
它们被称为移动构造函数和移动赋值
您可以像这样使用它们
int main()
{
A a;
A b(std::move(a)); //this will call move constructor, transfer the resource of a to b
A c;
a = std::move(c); //this will call move assignment, transfer the resource of c to a
}
你需要用std::move来包装a和c,因为它们有一个名字std::move告诉编译器将值转换成rvalue引用,不管在技术上参数是什么,std::move类似于"std::rvalue“
在移动后,unique_ptr的资源被转移到另一个unique_ptr
有许多主题记录了rvalue参考;this is a pretty easy one to begin with。
编辑:
moved object shall remain valid but unspecified state。
C++ primer 5,ch13也很好地解释了如何“移动”物体
https://stackoverflow.com/questions/16030081
复制相似问题