调用复制构造函数时如何复制内存?

时间:2018-11-01 11:02:58

标签: c++ compiler-optimization copy-constructor

我试图了解复制构造函数的行为以及如何创建和复制内存以及临时对象。我在g ++中禁用了复制省略功能,以更好地了解正在发生的事情。这是我的代码:

//====================
#include <iostream>
using namespace std;

class Human
{
public:
    Human()
    {
        cout << "Human constructed: " << this << endl;
    }

    Human(const Human &)
    {
        cout << "Human copied:      " << this << endl;
    }

    ~Human()
    {
        cout << "Human destroyed:   " << this <<  endl;
    }
};

class Creature
{
public:
    Creature()
    {
        cout << "Creature constructed: " << this <<  endl;
    }

    ~Creature()
    {
        cout << "Creature destroyed:   " << this <<  endl;
    }

    Human create_human()
    {
        Human mySecondHumanObject;
        return mySecondHumanObject;
    }
};


int main()
{
    Creature myCreatureObject;
    Human myFirstHumanObject = myCreatureObject.create_human();
    cout << "myFirstHumanObject :" << &myFirstHumanObject << endl;
    return 0;
}

输出:

Creature constructed: 0x7fff5b8d9d95
Human constructed: 0x7fff5b8d9d67    // mySecondHumanObject constructed
Human copied:      0x7fff5b8d9d97    // copied to where???
Human destroyed:   0x7fff5b8d9d67    // mySecondHumanObject destroyed at return
Human copied:      0x7fff5b8d9d96    // copied to myFirstHumanObject
Human destroyed:   0x7fff5b8d9d97    // object copied at return now destroyed
myFirstHumanObject :0x7fff5b8d9d96
Human destroyed:   0x7fff5b8d9d96
Creature destroyed:   0x7fff5b8d9d95

有人可以对这种机制的原理有所了解吗?我对为什么第一次执行复制构造函数感到困惑(复制到mem地址:0x7fff5b8d9d97)。为什么不直接将其直接复制到内存地址为0x7fff5b8d9d96的myFirstHumanObject中?

1 个答案:

答案 0 :(得分:2)

如果您要编写简单的myCreatureObject.create_human();而不将结果分配到任何地方,是否会创建Human并将其销毁?当然它将存在,您将看到输出。该函数返回一个值,因此必须使用该值创建一个临时对象。

由于您关闭了复制删除功能,因此即使要使用它来初始化另一个对象,也需要创建该临时文件。复制省略经常消除的不仅仅是一个副本。它可以消除整个链条。而当它关闭时,这些链条就会重新出现,就像您看到的那样。