Compilers can make a lot of optimizations (like inlining some functions), and I'm slightly suspicious that not all memory allocated for local variables is cleared after the function call in my program (based on the system monitor of the OS X), so that's why I'm asking: is it guaranteed by the standard that all destructors of the local variables would be called exactly at the moment they go out of scope?
Yes. Per paragraph 3.7.3 of the C++11 Standard:
Block-scope variables explicitly declared
register
or not explicitly declaredstatic
orextern
have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.
Notice, however, that this concerns variables with automatic storage duration. If you created an object dynamically with new
and assigned the result to a local raw pointer, then only the raw pointer will be destroyed, and not the pointed object:
{
int* foo = new int(42);
} // Here you have a memory leak: the foo pointer is destroyed,
// but not the object foo pointed to
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With