简体   繁体   English

为什么在赋值运算符之后在此代码中调用复制构造函数?

[英]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.

相关问题 为什么在这种情况下不调用赋值运算符而支持复制构造函数? - Why is the assignment operator not called in this case in favor of the copy constructor? 为什么在这种情况下都调用复制构造函数和赋值运算符 - why copy constructor & assignment operator both are called in this case 为什么在调用重载的赋值运算符时调用了拷贝构造函数? - why copy constructor is called at the time of calling overloaded assignment operator? 复制构造函数和赋值运算符都被调用 - Copy constructor and assignment operator both get called 为什么要为单个赋值操作调用复制构造函数和重载赋值运算符? - Why copy constructor and overloaded assignment operator are being called for a single assignment operation? 此代码中将调用哪个构造函数或赋值运算符? - Which constructor or assignment operator is getting called in this code? 复制构造函数,赋值运算符和析构函数代码重复 - Copy constructor, assignment operator, and destructor code duplication 为什么在没有赋值运算符的情况下调用转换构造函数? - Why is conversion constructor called in absense of assignment operator? 这是好的代码吗? (复制构造函数和赋值运算符) - Is this good code? (copy constructor and assignment operator ) 矩阵乘法后的赋值运算符和副本构造函数 - Assignment operator and copy constructor after matricies multiplication
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM