我在一本书上看到,它说:当我们使用另一个初始化新创建的对象时 - 使用复制构造函数创建一个临时对象,然后使用赋值运算符将值复制到新对象!
后来在书中我读到:当使用另一个对象初始化新对象时,编译器创建一个临时对象,使用复制构造函数将其复制到新对象。临时对象作为参数传递给复制构造函数。
真的很困惑,到底发生了什么!!
我认为这些说法都不正确 - 没有调用复制赋值运算符。
我会这样描述发生的事情:
当您创建一个新对象作为现有对象的拷贝时,将调用复制构造函数:
// creation of new objects
Test t2(t1);
Test t3 = t1;
只有当您赋值给一个已经存在的对象时,复制赋值运算符才会被调用
// assign to already existing variable
Test t4;
t4 = t1;
我们可以用下面的小例子来证明这一点:
#include <iostream>
class Test
{
public:
Test() = default;
Test(const Test &t)
{
std::cout << "copy constructor\n";
}
Test& operator= (const Test &t)
{
std::cout << "copy assignment operator\n";
return *this;
}
};
int main()
{
Test t1;
// both of these will only call the copy constructor
Test t2(t1);
Test t3 = t1;
// only when assigning to an already existing variable is the copy-assignment operator called
Test t4;
t4 = t1;
// prevent unused variable warnings
(void)t2;
(void)t3;
(void)t4;
return 0;
}
输出:
copy constructor
copy constructor
copy assignment operator
working example
我是一名优秀的程序员,十分优秀!