Why is the order of destruction of these function-local static objects NOT the inverse of their order of initialization?

末鹿安然 提交于 2019-12-03 15:48:49

The actual Standard text in C++14 [basic.start.term] is:

If the completion of the constructor or dynamic initialization of an object with static storage duration is sequenced before that of another, the completion of the destructor of the second is sequenced before the initiation of the destructor of the first. [Note: This definition permits concurrent destruction. —end note ]

In your code, two is constructed during the constructor of one. Therefore the completion of constructor of two is sequenced-before the completion of constructor of one.

So the completion of the destructor of one is sequenced-before the completion of the destructor of two, which explains what you are seeing.

Change your ctor to:

  One() {
    std::cout << "Start One construct" << std::endl;
    const char* twoval = GetTwo().value;
    std::cout << "twoval is: " << twoval << std::endl;
    std::cout << "Finish One construct" << std::endl;
  }

now you'll see that Two finishes construction before One does. So Two gets registered to be destroyed before One does, and gets destroyed after, because it was actually constructed (completely) first.

Start One construct
Two construct
twoval is: It's two!
Finish One construct
One destruct
twoval is: It's two!
Two destruct
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!