tags:

views:

126

answers:

2

When an object is created in your main() function, is its destructor called upon program termination? I would assume so since main() still has a scope( the entire program ), but I just wanted to make sure.

+15  A: 

It depends on how your program terminates. If it terminates by having main return (either by an explicit return or falling off the end), then yes, any automatic objects in main will be destructed.

But if your program terminates by calling exit(), then main doesn't actually go out of scope and any automatic objects will not be destructed.

R Samuel Klatchko
That's true for the use of exit in any function, isn't it ?
Benoît
@Benoit - yes, calling exit doesn't unwind the stack. If you call exit, no outstanding automatic variables in any function will get destructed.
R Samuel Klatchko
Yes. If the program terminates gracefully the destructors are called to clean up . This can easily be observed either by attaching a debugger or putting a printf in the destructor.
Jay D
+3  A: 

The scope of declarations inside main() is not the entire program. It behaves just like any normal function. So, yes, destructors of local class objects execute as expected. Unless the program terminates abnormally.

Hans Passant