3

可能重复:
什么是复制省略和返回值优化?

我有以下程序:

#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 调用我的复制构造函数?

4

1 回答 1

5

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

于 2012-11-28T23:44:46.150 回答