如果我修改赋值运算符使其返回对象 A 而不是对对象 A 的引用,那么有趣的事情就会发生。
每当调用赋值运算符时,复制构造函数就会立即被调用。这是为什么?
#include <iostream>
using namespace std;
class A {
private:
static int id;
int token;
public:
A() { token = id++; cout << token << " ctor called\n";}
A(const A& a) {token = id++; cout << token << " copy ctor called\n"; }
A /*&*/operator=(const A &rhs) { cout << token << " assignment operator called\n"; return *this; }
};
int A::id = 0;
A test() {
return A();
}
int main() {
A a;
cout << "STARTING\n";
A b = a;
cout << "TEST\n";
b = a;
cout << "START c";
A *c = new A(a);
cout << "END\n";
b = a;
cout << "ALMOST ENDING\n";
A d(a);
cout << "FINAL\n";
A e = A();
cout << "test()";
test();
delete c;
return 0;
}
输出如下:
0 ctor called
STARTING
1 copy ctor called
TEST
1 assignment operator called
2 copy ctor called
START c3 copy ctor called
END
1 assignment operator called
4 copy ctor called
ALMOST ENDING
5 copy ctor called
FINAL
6 ctor called
test()7 ctor called
最佳答案
因为如果您不返回对象的引用,它就会创建一个拷贝。 正如@M.M 所说的最后一次 test() 调用,由于复制省略 What are copy elision and return value optimization?,拷贝不会出现。
关于c++ - 为什么这段代码在赋值运算符之后调用了拷贝构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33819415/