引用“The C++ programming language”(特别版,第 4.9.6 节,“对象和左值”),众所周知:
[...] an object declared in a function is created when its definition is encountered and destroyed when its name goes out of scope
好的!在 4.9.4 节中:
A name can be used only in specific part of the program text. For a name declared in a function, that scope extends from its point of declaration to the end of the block in which its declaration occurs.
这听起来不错!
但我的问题是:当控件到达其 block 的末尾时,如何销毁(自动)变量?还有一个子问题:真的是这样吗?
例如:
int main()
{
int* c = 0;
{
int b = 999;
c = &b;
} // End of the scope of b...
std::cout << b; // ... so this is illegal
// But ...
std::cout << *c; // ... is OK, so 'b' has not really been destroyed
}
我了解到,由于函数调用中涉及的与堆栈相关的事情,局部变量在退出其函数范围时会被销毁。但是当退出一个简单的 {//... }
block 时,没有任何反应。
然后是一种特定的语言导致未定义的行为(在我的例子中,最后一个 cout
实际上是未定义的)但实际上在执行时没有影响(实际上没有执行任何操作来销毁对象)?
谢谢!
编辑 1:我不考虑静态变量。
编辑 2: 如果我很清楚变量是一个带有析构函数的对象,我问的是非对象变量。
最佳答案
您的示例中的代码确实是未定义的行为,它似乎可以在像这样的简单示例中工作。但是编译器可能会选择重新使用用于存储变量 b 的槽。或者它可能由于函数调用而将数据压入堆栈而被销毁。
关于c++ - 关于作用域和生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3600712/