The quote is "C ++ Programming Language" (special edition, section 4.9.6, "Objects and Lvalues") and, as you know:
[...] an object declared in a function is created when its definition is encountered and destroyed when its name goes beyond the scope
OK! And in section 4.9.4:
The name can be used only in a certain part of the program text. For a name declared in a function, this area extends from its declaration point to the end of the block in which it is declared.
All this sounds normal!
But my question is: how can a (auto) variable be destroyed when the control reaches the end of its block? And the subquery: is this really so?
For instance:
int main() { int* c = 0; { int b = 999; c = &b; }
I understand that a local variable is destroyed when it leaves the scope of its function due to stack-related things related to calling the function. But when you exit a simple block { // ... } nothing happens.
Is this a specific language that leads to undefined behavior (in my case, the last cout is actually undefined), but it is practically without effect on execution (nothing is actually done to destroy the object)
Thanks!
Edit 1: I do not consider static variables.
Edit 2: In the case where the variable is an object with a destructor, it was clear to me, I asked about non-target variables.
source share