动态分配的对象(通俗语言中的"堆对象")永远不是变量.因此,它们永远不会超出范围.他们不住在任何范围内.您可以处理它们的唯一方法是通过分配时获得的指针.
(指针通常分配给变量,但这没有帮助.)
重复:变量有范围; 对象没有.但是很多对象都是变量.
并回答这个问题:你只能释放对象,而不是变量.
小智 6
闭合的“}”大括号的末尾是堆栈“释放”其内存的地方。所以如果我有:
{
int a = 1;
int b = 2;
{
int c = 3; // c gets "freed" at this "}" - the stack shrinks
// and c is no longer on the stack.
}
} // a and b are "freed" from the stack at this last "}".
Run Code Online (Sandbox Code Playgroud)
您可以将 c 视为在堆栈上比“a”和“b”“更高”,因此 c 在它们之前弹出。因此,每次写入“}”符号时,您都在有效地缩小堆栈并“释放”数据。
了解函数调用 - 每次调用都会将数据和函数地址推送到堆栈上。函数从堆栈中弹出数据并最终推送其结果。
一般来说,堆栈由操作系统管理,是的 - 它可能会被耗尽。尝试做这样的事情:
int main(int argc, char **argv)
{
int table[1000000000];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这应该足够快地结束。