Quoting “The C++ programming language” (special edition, section 4.9.6, “Objects and Lvalues”), and as is well known:
[…] an object declared in a function is created when its definition is encountered and destroyed when its name goes out of scope
OK ! And in section 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.
This all sounds fine !
But my question is: how can an (auto) variable be destroyed when the control reach the end of its block? And a subquestion: Is it actually the case ?
For example:
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
}
I understand that a local variable is destroyed when quitting the scope of its function because of the stack related things involved in a function call. But when quitting a simple { // ... } block, nothing happens.
Is it then a language specific that leads to undefined behavior (in my case the last cout is actually undefined) but that is in practice without effect at execution (nothing is actually executed to destroy the object) ?
Thanks !
Edit 1: I am not considering static variables.
Edit 2: In case where the variable is an object with a destructor was clear to me, I was asking about non object variables.
The code in your sample is indeed undefined behavior, and it will appear to work in simple examples like this. But the compiler may choose to reuse the slot used to store variable b. Or it may be destroyed as the result of data being pushed on the stack because of a function call.