Function called upon destruction of an object

Could you provide a code example reflecting the following rule:

N3797 C ++ 14, section 3.6.3 / 2:

If any function contains an object with the scope of the static or thread object, the storage time that was destroyed and the function was called during the destruction of the object with static or thread storage duration, the program has undefined behavior if the control flow passes through the definition of a previously destroyed block-area an object.

+4
source share
2 answers

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 , . c, theFunction(), - foo.

. , foo , c. , d , theFunction(), foo .

, , undefined.

+10
struct Counter {
  int *ptr;
  Counter() {ptr = new int; *ptr = 0;};
  int next() {return (*ptr)++;}
  ~Counter() {delete ptr;}
};

int function() {
  static Counter c;
  return c.next();
}

struct Obj {
  ~Obj() {cout<<function()<<endl;}  
};

Obj obj;

int main() {
  cout<<function()<<endl;
}

obj. c. , , Counter c obj. obj , , ... undefined.

0

Source: https://habr.com/ru/post/1547420/


All Articles