堆栈变量超出范围时是否解除分配?

Is the stack variable deallocated when it goes out of scope?

本文关键字:是否 解除分配 范围 变量 堆栈      更新时间:2023-10-16

sample1.cpp

#include <iostream>
int main()
{
int* aPtr = nullptr;
{
int a = 3;
aPtr = &a;
}
std::cout << *aPtr << std::endl;
return 0;
}

输出

3

我能够通过aPtr访问a

  1. 这是否意味着a即使在它退出后也不会被释放 范围。
  2. 这是否意味着a仅在函数之后才被释放 它的定义是展开的。
  3. 或者这是当前输出某些值的未定义行为?

桑佩2.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

正如评论中提到的,在这两种情况下,您都面临着未定义的行为(因此允许发生任何事情(。堆栈变量一旦超出范围就会被销毁,它们占用的内存被释放,尽管通常它不会立即被覆盖(至少在上面这样的简单情况下(,因此指向此类变量的指针有时可能会表现出或多或少的"有效"属性(就像看起来对象仍然有效(, 尽管它明显悬而未决。