Is the C++ compiler optimizer allowed to break my destructor ability to be called multiple times?

后端 未结 2 2015
鱼传尺愫
鱼传尺愫 2021-01-06 07:47

We once had an interview with a very experienced C++ developer who couldn\'t answer the following question: is it necessary to call the base class destructor from the de

相关标签:
2条回答
  • 2021-01-06 07:53

    Calling the destructor converts an object into raw memory. You cannot destruct raw memory; this is undefined behaviour. The C++ compiler is entitled to do anything it wants. While it is unlikely that it will turn your computer in cottage cheese, it might deliberately trigger a slap-on-the-wrist SEGFAULT (at least in debug mode).

    0 讨论(0)
  • 2021-01-06 08:02

    Standard 12.4/14

    Once a destructor is invoked for an object, the object no longer exists; the behavior is undefined if the destructor is invoked for an object whose lifetime has ended (3.8).

    So I guess the compiler should be free to optimize away the setting of buffer to null since the object no longer exists after calling the destructor.

    But even if the setting of the buffer to null wasn't removed by the compiler, it seems like calling the destructor twice would result in UB.

    0 讨论(0)
提交回复
热议问题