首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用unique_ptr复制类的构造函数

使用unique_ptr复制类的构造函数
EN

Stack Overflow用户
提问于 2013-04-16 14:21:30
回答 4查看 101.1K关注 0票数 126

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-04-16 14:24:20

由于unique_ptr不能共享,因此您需要深度复制其内容或将unique_ptr转换为shared_ptr

代码语言:javascript
复制
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可移动。

代码语言:javascript
复制
A( A&& a ) : up_( std::move( a.up_ ) ) {}

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

代码语言:javascript
复制
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与仅移动类型一起使用。

票数 98
EN

Stack Overflow用户

发布于 2014-11-24 19:50:41

尝试使用此帮助器创建深层副本,并在源unique_ptr为空时进行处理。

代码语言:javascript
复制
    template< class T >
    std::unique_ptr<T> copy_unique(const std::unique_ptr<T>& source)
    {
        return source ? std::make_unique<T>(*source) : nullptr;
    }

例如:

代码语言:javascript
复制
class My
{
    My( const My& rhs )
        : member( copy_unique(rhs.member) )
    {
    }

    // ... other methods

private:
    std::unique_ptr<SomeType> member;
};
票数 14
EN

Stack Overflow用户

发布于 2013-04-16 14:32:34

丹尼尔·弗雷提到了拷贝解决方案,我想谈谈如何移动unique_ptr

代码语言:javascript
复制
#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_;
};

它们被称为移动构造函数和移动赋值

您可以像这样使用它们

代码语言:javascript
复制
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也很好地解释了如何“移动”物体

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16030081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档