Function, called during the object destruction

c++, destructor

Solution

Here you are:

void theFunction()
{
  static std::unique_ptr<int> foo { new int(42) };
}

struct Creator
{
  Creator() { theFunction(); }
};


struct Destroyer
{
  ~Destroyer() { theFunction(); }
};

Destroyer d;
Creator c;

int main()
{}

`d` is created first, but its constructor does nothing. Then, `c` is created, and as part of its initialisation, `theFunction()` is called, which causes the block-scope static-storage-duration variable `foo` to be initialised.

Then, at program exit, static-storage objects are destroyed in reverse order of construction. So `foo` is destroyed, and then `c`. Finally, `d` is destroyed, but its destructor calls `theFunction()`, which causes control flow to reach the definition of `foo` again, after it's been destroyed already.

The standard quote you've shown ascribes undefined behaviour to this.

Problem

Could you provide code example reflecting the following rule: N3797 c++14, section 3.6.3/2: If a function contains a block-scope object of static or thread storage duration that has been destroyed and the function is called during the destruction of an object with static or thread storage duration, the program has undefined behavior if the flow of control passes through the definition of the previously destroyed block-scope object.

Original source