To my understanding , a return instruction in any function, should lead to leaving the function block and calling the destructor of local objects.
In addition to this ,the return x; from the main() function calls exit(x);.
If this is true, could someone explain me the output from the following code ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class A{
public:
A(){cout<<"constr ";}
~A(){cout<<"destruct ";}
};
A a;
int main(){
A b;
cin.sync();
cin.ignore();
return 0;
}
The code prints two times "constr" for both objects, a in global scope, and b in local scope. However "destruct" doesn't get printed not even once.
I tried out your code and the destructors actually do get called. However, you have to be quick to see it: the text appears just after you press Enter, as the console is closing. Hence, your understanding in your first statement is correct!
return 0; doesn't destroy objects, it returns control back to the caller. The operating system.
main() doesn't need a return statement.
Objects declared at global or main() scope created with static storage duration (not using dynamic memory by creating with new) are destroyed after main() exits.
The destructors definitely get called, but I suspect that the behavior of destroying the global A is undefined. That's because you're using std::cout and it's completely possible that it has been destroyed already.
you're using std::cout and it's completely possible that it has been destroyed already.
std::cout (and other predefined streams) takes special measures to be available in constructors and destructors of static objects (as long as #include <iosream> is visible), although it was underspecified until C++11