相当于离题,但它不会真正适合在评论中,并且似乎存在一些分歧。尝试使用以下代码片段,以了解何时调用复制构造函数和赋值运算符:
class A
{
public:
A() { cout << "A::A()
"; }
A(const A &) { cout << "A::A(const A &)
"; }
void operator =(const A &) { cout << "A::operator=(const A &)
"; }
};
int main()
{
A a; // default constructor
A copy = a; // copy constructor (and no assignment operator)
A copy2(a); // copy constructor (and no assignment operator)
a = copy; // assignment operator
A function(); // declares a function return A
A b = A(); // default constructor (but no assignment operator)
A b2 = A(a); // copy constructor (but no assignment operator)
}