使用unique_ptr复制类的构造函数 [英] Copy constructor for a class with unique_ptr

查看:173
本文介绍了使用unique_ptr复制类的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为具有 unique_ptr 成员变量的类实现复制构造函数?我只考虑使用C ++ 11。

How do I implement a copy constructor for a class that has a unique_ptr member variable? I am only considering C++11.

推荐答案

由于 unique_ptr 无法共享,您需要深度复制其内容或将 unique_ptr 转换为 shared_ptr

Since the unique_ptr can not be shared, you need to either deep-copy its content or convert the unique_ptr to a 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所述,您可以使用move-ctor代替副本-ctor,但这会导致类的语义不同。 move-ctor需要通过 std :: move

You can, as NPE mentioned, use a move-ctor instead of a copy-ctor but that would result in different semantics of your class. A move-ctor would need to make the member as moveable explicitly via std::move:

A( A&& a ) : up_( std::move( a.up_ ) ) {}

拥有一整套必需的运算符也会导致

Having a complete set of the necessary operators also leads to

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 ,您基本上必须确定vector是否是对象的唯一所有者,在这种情况下,使类可移动就足够了,但是不可复制。如果省略了copy-ctor和copy-assignment,则编译器将指导您如何将std :: vector与仅移动类型一起使用。

If you want to use your class in a std::vector, you basically have to decide if the vector shall be the unique owner of an object, in which case it would be sufficient to make the class moveable, but not copyable. If you leave out the copy-ctor and copy-assignment, the compiler will guide your way on how to use a std::vector with move-only types.

这篇关于使用unique_ptr复制类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆