[英]Why is the copy constructor called in this code after the assignment operator?
If I modify the assignment opreator so that it returns an object A instead of a reference to an object A then something funny happens. 如果我修改赋值运算器,以便它返回对象A而不是对对象A的引用,则会发生一些有趣的事情。
Whenever the assignment operator is called, the copy constructor is called right afterwards. 每当调用赋值运算符时,此后立即调用复制构造函数。 Why is this?
为什么是这样?
#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;
}
The output is as follows: 输出如下:
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
Because if you don't return a reference of the object it makes a copy. 因为如果不返回该对象的引用,它将创建一个副本。 As @MM said about the final test() call, the copy does not appears because of the copy elision What are copy elision and return value optimization?
正如@MM关于最后的test()调用所说的,由于复制省略而不会出现复制。 什么是复制删除和返回值优化?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.