C++对象存储在栈或堆中

C++ Object is stored in stack or heap

我知道这个问题在 Object creation on the stack/heap? 中被问了很多 据我了解,如果一个对象存储在 Stack 中,如果变量超出范围,它将被弹出。但是当涉及到自动存储时,我很困惑它怎么不在堆中。我读过不推荐在 C++ 中使用 new 和 delete(甚至是邪恶这个词的选择),因为它会引入内存泄漏。所以我设置了这样的测试代码

#include <iostream>
#include <string>

class Cat
{
public:
    Cat(const std::string& name)
    {
        this->name = name;
        std::cout << "construct Cat " << this->name << std::endl;
    }
    ~Cat()
    {
        std::cout << "destruct Cat " << this->name << std::endl;
    }
    void feed()
    {
        std::cout << "feed Cat " << this->name << std::endl;
    }
private:
    std::string name;
};

Cat createFelix()
{
    Cat garfield("Garfield");
    Cat felix("Felix");
    garfield.feed();
    felix.feed();
    return felix;
}

void getAndFeedFelix()
{
    Cat justFelix = createFelix();
    justFelix.feed();
}

int main()
{
    getAndFeedFelix();
    std::cout << "bla bla blah" << std::endl;
}

结果是这样的

construct Cat Garfield
construct Cat Felix
feed Cat Garfield
feed Cat Felix
destruct Cat Garfield
feed Cat Felix
destruct Cat Felix
bla bla blah

所以在我的结论中,函数 createFelix() 是从 getAndFeedFelix() 调用的,它 return 编辑了一只猫(存储在堆栈中),它应该在之后从堆栈中弹出函数 return,但由于自动存储机制,对象在 getAndFeedFelix() 超出范围后被破坏。这怎么会发生?如果自动存储正在使用堆和引用计数,那么它可能是可能的。我的逻辑错了吗?

您发现了Return Value Optimization(具体命名为return价值优化)。

这个函数:

Cat createFelix()
{
    Cat felix("Felix");
    return felix;
}

Cat justFelix = createFelix();

看起来应该创建一个 Cat,复制它,然后销毁它。但作为一种优化,createFelix() 实际上在 justFelix 拥有的内存中创建了 felix。所以我们只创建一个 Cat,零拷贝。这里的一切都在堆栈上。

那么:

void getAndFeedFelix()
{
    Cat justFelix = createFelix(); // creates a cat
    justFelix.feed();              // feeds a cat
}                                  // destroys a cat

这是您看到的输出。