Does "return x" in main() destruct objects ?

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!
closed account (E0p9LyTq)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

class A
{
public:
   A() { std::cout << "Hello...\n"; }
   ~A(){ std::cout << "Good-bye...\n"; }
};

A global;

int main()
{
   A local;

   std::cout << "\nExiting main()...\n\n";
}


Hello...
Hello...

Exiting main()...

Good-bye...
Good-bye...


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.

http://en.cppreference.com/w/cpp/language/main_function
Last edited on
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.
For some nooby reason I was waiting for the destructor to get called before pressing enter...
All is clear now, thanks guys :)
closed account (E0p9LyTq)
Storage duration can be a bit confusing when beginning to learn C++. :)

http://en.cppreference.com/w/cpp/language/storage_duration
dhayden wrote:
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
Last edited on
Topic archived. No new replies allowed.