复制构造器 和 复制-赋值操作符 的 区别

 

本文地址:  

 

复制构造器(copy constructor):定义新对象, 则调用复制构造器(constructor);

复制-赋值操作符(copy-assignment operator):没有定义新对象, 不会调用构造器;

注意一个语句, 只能使用一个方式, 并不是出现"=", 就一定调用复制-赋值操作符, 构造器有可能优先启用.

代码:

#include 
class Widget { public: Widget () = default; Widget (const Widget& rhs) { std::cout << "Hello girl, this is a copy constructor! " << std::endl; } Widget& operator= (const Widget& rhs) { std::cout << "Hello girl, this is a copy-assignment operator! " << std::endl; return *this; } }; int main (void) { Widget w1; Widget w2(w1); //使用copy构造器 w1 = w2; //使用copy-assignment操作符 Widget w3 = w2; //使用copy构造器 }

输出:

Hello girl, this is a copy constructor!   Hello girl, this is a copy-assignment operator!   Hello girl, this is a copy constructor!