Compilers can do many optimizations (e.g. embedding some functions), and I'm a little suspicious that not all memory allocated for local variables is cleared after the function is called in my program (based on the OS X system monitor), so I ask: is it guaranteed by the standard that all destructors of local variables will be called exactly at the moment when they go out of scope?
Yes. For paragraph 3.7.3 of the C ++ 11 standard:
, register static extern, . , , .
register
static
extern
, . new , , :
new
{ int* foo = new int(42); } // Here you have a memory leak: the foo pointer is destroyed, // but not the object foo pointed to
, .
, . , , , .
, , , valgrind, drMemory Google (google " " ). , , , ..
, , , , .
2 (3.7.3) , - . , , block (6.6).
, :
void f() { A a; // create a local instance of A // memory will be allocated on the stack, // and the constructor for `a` will be called. // various code here // here at the end of the scope, // the destructor for `a` will be called, // and the memory on the stack will be freed. }
[11.5] ?
!
The destructor will be called again at the end} of the block in which the local was created. This is a guarantee of language; this happens automatically; there is no way to stop it. But you can get very bad results from calling the destructor on the same object a second time! Explosion! You are dead!
This is slightly different from your question, but the base is the same.