2
votes

C++ standard section 3.6.1 says that

Calling the function std::exit(int) declared in <cstdlib> terminates the program without leaving the current block and hence without destroying any objects with automatic storage duration If std::exit is called to end a program during the destruction of an object with static storage duration, the program has undefined behavior.

So, consider following simple program

#include <iostream>
#include <cstdlib>
class test
{
    public:
        test()
        {
            std::cout<<"constructor\n";
        }
        ~test()
        {
            std::cout<<"destructor\n";
        }
};
int main()
{
    test t;
    exit(0);
}

The output of the above program should be obviously

constructor

So, my question is:

  1. when the automatic object t will be destroyed?

  2. Will it be safely destroyed by compiler?

  3. Why it is undefined behavior?

Now, consider slightly modified version of above program.

#include <iostream>
#include <cstdlib>
class test
{
    public:
        test()
        {
            std::cout<<"constructor\n";
        }
        ~test()
        {
            std::cout<<"destructor\n";
        }
};
int main()
{
    static test t;
    exit(0);
}

Now, I got following output:

constructor

destructor

So, is it possible to see only constructor call as an output on some C++ implementations due to undefined behavior?

Please correct me If I understood incorrectly something.

1
Side note: Calling exit is for programmers ending at a stake. - user2249683

1 Answers

3
votes
  1. when the automatic object t will be destroyed?

Never. The quote you cited reads "... without destroying any objects with automatic storage duration ..."

  1. Will it be safely destroyed by compiler?

No. The compiler's job is to produce the code for the machine to run, once you're at runtime the compiler isn't doing anything anymore.

  1. Why it is undefined behavior?

In your example, it's not undefined behavior - you're not calling std::exit() "during the destruction of an object with static or thread storage duration." However, if you were, it would be sufficient to answer "it's undefined behavior because the standard explicitly states it as such."