![](/img/trans.png)
[英]Why is the assignment operator not called in this case in favor of the copy constructor?
[英]Why is the copy constructor called in this code after the assignment operator?
如果我修改賦值運算器,以便它返回對象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
因為如果不返回該對象的引用,它將創建一個副本。 正如@MM關於最后的test()調用所說的,由於復制省略而不會出現復制。 什么是復制刪除和返回值優化?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.