Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the destructor of the local variable always guaranteed to be called when it goes out of scope?

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?

like image 928
lizarisk Avatar asked Apr 28 '13 17:04

lizarisk


1 Answers

Yes. Per paragraph 3.7.3 of the C++11 Standard:

Block-scope variables explicitly declared register or not explicitly declared static or extern 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
like image 137
Andy Prowl Avatar answered Nov 07 '22 05:11

Andy Prowl