【问题标题】:Why my copy constructor not called? [duplicate]为什么我的复制构造函数没有被调用? [复制]
【发布时间】:2012-11-16 23:22:55
【问题描述】:

可能重复:
What are copy elision and return value optimization?

我有以下程序:

#include <iostream>

using namespace std;

class Pointt {
public:
    int x;
    int y;

    Pointt() {
        x = 0;
        y = 0;
        cout << "def constructor called" << endl;
    }

    Pointt(int x, int y) {
        this->x = x;
        this->y = y;
        cout << "constructor called" << endl;
    }

    Pointt(const Pointt& p) {
        this->x = p.x;
        this->y = p.y;
        cout << "copy const called" << endl;
    }

    Pointt& operator=(const Pointt& p) {
        this->x = p.x;
        this->y = p.y;
        cout << "op= called" << endl;
        return *this;
    }
};

Pointt func() {
    cout << "func: 1" << endl;
    Pointt p(1,2);
    cout << "func: 2" << endl;
    return p;
}


int main() {
    cout << "main:1" << endl;
    Pointt k = func();
    cout << "main:2" << endl;
    cout << k.x << " " << k.y << endl;
    return 0;
}

我期望的输出如下:

main:1
func: 1
constructor called
func: 2
copy const called
op= called
main:2
1 2

但我得到以下信息:

main:1
func: 1
constructor called
func: 2
main:2
1 2

问题是:为什么不从 func 返回一个对象到 main 调用我的复制构造函数?

【问题讨论】:

  • 我理解你为什么期望调用复制构造函数,但你不应该期望调用赋值运算符。在初始化中使用“=”时,实际上不是赋值运算符,而是复制初始化(在这种情况下已被优化)。如果没有优化,将有 2 次调用复制构造函数。

标签: c++ operator-overloading copy-constructor


【解决方案1】:

这是由于Return Value Optimization。这是少数允许 C++ 更改程序行为以进行优化的实例之一。

【讨论】:

    猜你喜欢
    • 2018-02-04
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多