繁体   English   中英

堆栈上的C ++变量在函数作用域的末尾似乎没有被释放

[英]C++ variable on stack does not appear to be freed at end of function scope

我编写了以下简短代码进行实验,并尝试获得对象具有其构造函数和析构函数的“第一手”体验:

class Foo
{
public:
    Foo(int bar)
    {
        this->bar = bar;
        std::cout << "Standard constructor called" << std::endl;
    }
    ~Foo()
    {
        std::cout << "Standard destructor called" << std::endl;
    }
    Foo(const Foo &foo)
    {
        std::cout << "Copy constructor called" << std::endl;
        this->bar = foo.bar;
    }
    inline int get_bar() { return bar; }
private:
    int bar;
};

Foo make_foo(int bar)
{
    Foo f1(bar);
    std::cout << "About to return foo with address of: " << &f1 << std::endl;
    return f1;
}

int main()
{
    Foo f2 = make_foo(3);
    std::cout << "New variable has address of: " << &f2 << std::endl;
    std::cout << "And a value of " << f2.get_bar() << std::endl;
}

但是,当我运行此代码时,我发现有些奇怪。 如预期的那样,将打印“标准构造函数调用”,并打印该函数中foo的地址。 但是当函数结束时,没有调用任何析构函数,并且f2实际上具有与f1相同的内存地址,尽管据我所知,f1应该已经超出范围并由于其位于堆栈上而被释放了内存,对吗? 还是在这种情况下不是预期的结果?

我的期望是将调用复制构造函数将f1复制到f2,然后f1将调用其析构函数,而f2将占用其他内存地址。

如果有人好奇,这是实际输出:

Standard constructor called                                                                          
About to return new foo with address of: 0x7fff518e5a88                                              
New variable has address of: 0x7fff518e5a88                                                          
And a value of 3                                                                                     
Standard destructor called     

有趣的是,当我将make_foo的返回类型make_foo为引用类型时,该函数几乎按照我的期望执行,f1被销毁,f2复制垃圾数据。

这是一种特定的情况,当返回给变量分配给我应该注意的另一个变量时,堆栈上的变量将不会释放其内存吗?

编译器正在执行返回值优化(RVO)。 您可以在此处阅读有关内容: https : //en.wikipedia.org/wiki/Copy_elision#Return_value_optimization

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM