c++ - 为什么我的复制构造函数没有被调用?

标签 c++ operator-overloading copy-constructor

<分区>

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

最佳答案

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

关于c++ - 为什么我的复制构造函数没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13616425/

相关文章:

c++ - 文本文件到数组传输

c++ - 友元函数 = 两个不同类的运算符重载

c++ - 自由 operator->* 重载是邪恶的吗?

c++ - 是否可以在 C++ 中重载 ""?

c++ - 如何在复制控制函数中处理 C++ 数组成员?

c++ - 为什么我不能在我的复制构造函数中使用 std::copy?

c++ - 从双端队列中删除某个位置的对象

C++11 - enable_if - 类定义之外的函数实现

c++ - CvQuadEdge2D 在 OpenCV 3 中是否具有等效项

c++ - 在初始化时强制执行赋值运算符而不是复制构造函数?