> This particular compiler (tried with a few different versions of GCC) seems to be
> allocating the structure at function entry and de-allocating at function exit.
If the constructor and destructor of
myStructure has no observable side-effects, the 'as-if' rule allows the implementation to do so.
http://en.cppreference.com/w/cpp/language/as_if
Try this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
struct myStructure
{
myStructure() { std::cout << "\t*** myStructure::constructor\n" ; }
~myStructure() { std::cout << "\t*** myStructure::destructor\n" ; }
};
int main()
{
{
std::cout << "entered a block-scope, creating an object\n" ;
myStructure aStructure ;
std::cout << "just before exiting block-scope\n" ;
}
std::cout << "exited block-scope\n" ;
}
|
http://coliru.stacked-crooked.com/a/f1e8b402eb755a37
> I've been unable to find a qualified reference stating that
> the memory is returned to the stack at the end of the block
C++ does not use terms like 'stack variable' or 'return memory to the stack'; the life-time of objects is specified in terms of an abstract concept called 'storage duration'. The standard is only concerned about the lifetime of an object (and the duration for which the storage for an object would be available).
For objects with
automatic storage duration, the storage for the object is required only from the beginning of the enclosing code block and this storage can be deallocated or re-used on exiting from the code block. In practice, most implementations use the run-time stack for this kind of reclaimable storage; but that is technically an implementation detail.
This is what the IS has to say about the life-time of objects with automatic storage duration:
Block-scope variables not explicitly declared static, thread_local, or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.
...
Variables with automatic storage duration are initialized each time their declaration-statement is executed. Variables with automatic storage duration declared in the block are destroyed on exit from the block. |