拷贝构造和operator=的区别

时间:2022-06-11 09:25:47
简单总结下:

对于在赋值操作之前,还未构造的变量,调用拷贝构造函数(Copy Constructor);

对于在赋值之前,已经构造的变量,调用赋值操作(Assignment Operator);

#include <iostream>


class A
{
public:
A(){ std::cout << "A()" << std::endl; };
A(const A& rhs){ std::cout << "copy constructor" << std::endl;; }
A& operator=(const A& rhs){ std::cout << "operator=" << std::endl; return *this; }
};
A test()
{
A a;
return a;
}
int main()
{
A a;
A b = a; // copy constructor


A c;
c = a; // operator=


c = test(); // operator=


A d = test(); // copy constructor
}