简体   繁体   English

如何复制构造函数和移动构造函数

[英]How copy constructor and move constructor work

My problem is to understand how exactly these two constructors work. 我的问题是要了解这两个构造函数究竟是如何工作的。 I have this class: 我有这门课:

class moveClass
{
  int variabile;
  public:
  moveClass(){} 
      //move constructor
  moveClass(moveClass && arg)
  {
    cout<<"Call move constructor"<<endl;
    variabile = arg.variabile;
  } 
      //copy constructor
  moveClass(const moveClass & arg)
  {
    cout<<"Call copy constructor"<<endl;
    variabile = arg.variabile;
  }  
};

From what i understand, when i instance a new object of this class, a constructor is called based on the type of the parameter. 根据我的理解,当我实例化该类的新对象时,将根据参数的类型调用构造函数。

The advantage of the move constructor is that when an rvalue is used to instance an object, that object isn't copied, but just moved. 移动构造函数的优点是当rvalue用于实例化对象时,该对象不会被复制,而只是被移动。

1 moveClass a;
2 moveClass b = a;
3 moveClass c = std::move(a);

Considering this example, can i say that when i instance b, a is copied, then assigned to b? 考虑到这个例子,我可以说当我实例b时,a被复制,然后分配给b?

In other words up until line 2 i will have 3 objects in memory: a, b and a_copy. 换句话说,直到第2行,我将在内存中有3个对象:a,b和a_copy。

While line 3 will just create the c object and no new copy objects. 而第3行只会创建c对象而没有新的复制对象。

Basically at the end of these three lines i will have in memory 4 objects. 基本上在这三行的末尾,我将在内存中有4个对象。 Is this correct? 它是否正确?

The code of the constructors is also the same, so i expect that the only difference is the type of the argument passed. 构造函数的代码也是一样的,所以我希望唯一的区别是传递的参数的类型。

In other words up until line 2 i will have 3 objects in memory: a, b and a_copy. 换句话说,直到第2行,我将在内存中有3个对象:a,b和a_copy。

No. 没有。

moveClass b = a;

is the same as 是相同的

moveClass b(a);

So, the copy constructor for b is called and you directly copy the members from a into b , no temporary(copy) is generated. 因此,调用b的复制构造函数并直接将成员从a复制到b ,不生成临时(复制)。

At then end of it all you have only constructed 3 objects, a , b and c . 在它结束时,你只构建了3个对象, abc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM