且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

超出范围时,是否释放了堆栈变量?

更新时间:2022-01-02 00:41:36

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

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.