c++ - 为什么这段代码在赋值运算符之后调用了拷贝构造函数?

标签 c++

如果我修改赋值运算符使其返回对象 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/

相关文章:

C++ 禁用忙碌/等待光标

c++ - 是否可以重载 C++11 new 运算符来创建智能指针?

c++ - 添加一个函数调用时应用程序幻影崩溃

JavaCv/OpenCv 错误 : what does it mean?

c++ - 使用 Qt 仅制作一个窗口以在其中快速渲染 opengl

c++ - MT还是MD用于静态释放?

c++ - 使用堆栈获取 BST 的高度

c++ - 我想从一个字符串句子中取出单词并在 C++ 中得到这个错误

c++ - 从函数调用返回 Mat 时出现奇怪的结果

c++ - "missing type specifier"构造函数声明错误