Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is not deleting an object that has a destructor with a side effect undefined behavior in C++11?

This answer quotes C++11 Standard 3.8:

if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.

The part about the destructor not being called is clear. Now suppose the skipped destructor had a side effect that should have affected the program behavior.

Why is the program behavior undefined now? Why wouldn't the side effects be skipped (since the destructor is not called) and the program run normally just without side effects applied?

like image 547
sharptooth Avatar asked Apr 02 '12 06:04

sharptooth


2 Answers

The important part is the first part of that paragraph (emphasis mine):

A program may end the lifetime of any object by reusing the storage which the object occupies ...

If you simply reuse the storage for an object whose destructor has not been called, then you get undefined behaviour. For example, the object could have started a thread, or registered a callback, or some other action where an external component might expect the object to still exist.

like image 77
Greg Hewgill Avatar answered Oct 14 '22 10:10

Greg Hewgill


In this case, we do have a precise answer. The specific line was introduced to resolve CWG 1116, "Aliasing of union members".

like image 44
MSalters Avatar answered Oct 14 '22 09:10

MSalters