超出范围时,是否释放了堆栈变量? [英] Is the stack variable deallocated when it goes out of scope?

查看:86
本文介绍了超出范围时,是否释放了堆栈变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>

int main()
{
    int* aPtr = nullptr;

    {
        int a = 3;
        aPtr = &a;
    }

    std::cout << *aPtr << std::endl;

    return 0;
}

输出

3

我能够通过 aPtr 访问 a


  1. 这意味着 a 即使从$ b中消失也不会被释放$ b范围。

  2. 这意味着 a 仅在定义的
    中的函数展开后才被释放。

  3. 还是这是当前输出某些值的未定义行为?

  1. Does that mean a is not deallocated even after it goes out of scope.
  2. Does that mean a is deallocated only after the function in which it is defined unwinds.
  3. Or is this an undefined behavior that currently outputs some value?



sampe2 .cpp



sampe2.cpp

#include <iostream>

struct Box
{
    Box(int a_)
        :a(a_)
    {}

    int getValue() const { return a;}

    ~Box()
    {
        std::cout << "Destructor called" << std::endl;
    }
private:
    int a;
};


int main()
{
    Box* boxPtr = nullptr;

    {
        Box box = 23;
        boxPtr = &box;
    }

    std::cout << boxPtr->getValue() << std::endl;

    return 0;
}

输出

Destructor called
23

即使在破坏了 box boxPtr 访问 box

I am able to access box through boxPtr even after destructor of box is called.

推荐答案

如注释中所述,在两种情况下,您都面临不确定的行为(因此,允许发生)。堆栈变量一旦超出范围就会被销毁,它们所占用的内存将被释放,尽管通常它不会立即被覆盖(至少在上述简单情况下如此),因此指向该变量的指针有时可能会显示更多或更少的有效属性(看起来像对象仍然有效),尽管它显然是悬空的。

As mentioned in the comments, in both cases you are facing undefined behavior (so anything is allowed to happen). The stack variables are destroyed as soon as they go out of scope, the memory occupied by them is freed, although usually it's not immediately overwritten (at least in simple cases like above), therefore the pointer pointing at such variable, might sometimes exhibit more or less "valid" properties (as in it looks like the object is still valid), despite it clearly dangling.

这篇关于超出范围时,是否释放了堆栈变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆