Why is an object with a destructor with undefined side effect behavior not being deleted in C ++ 11?

This answer quotes C ++ 11 Standard 3.8:

if there is no explicit call to the destructor or if the delete expression (5.3.5) is not used to free the repository, the destructor should not be implicitly called and any program that depends on the side effects created by the destructor has unstable behavior.

The part about a non-callable destructor is understandable. Now suppose that a missed destructor had a side effect that was supposed to affect program behavior.

Why is program behavior undefined now? Why not skip side effects (since the destructor is not called), and the program works fine without side effects?

+9
c ++ undefined-behavior memory-leaks c ++ 11 destructor
Apr 2 2018-12-12T00:
source share
4 answers

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

A program can end the lifetime of any object by reusing the storage that the object takes ...

If you simply reuse storage for an object whose destructor has not been called, you will get undefined behavior. For example, an object might start a thread or register a callback or some other action in which an external component might expect the object to still exist.

+5
Apr 02 2018-12-12T00:
source share

In this case, we have the exact answer. A specific line has been introduced to enable CWG 1116 , Merge Member Members.

+3
Apr 02 2018-12-12T00:
source share

Your question does not make sense.

Why not skip side effects (since the destructor is not called), and the program starts normally without side effects?

They are omitted because they would be called by the destructor and not called.

My reading:

and any program that depends on the side effects created by the destructor has undefined behavior.

just, I view it in the light of RAII. Example:

#include "Object.hpp" struct Manager: private boost::noncopyable { union Raw { char _[sizeof(Object)]; Object o; }; static Raw raw; Manager() { new (raw.o) Object(); } ~Manager() { raw.o.~Object(); } }; 

Now, if I select Manager , forgets to destroy it and allocates a new one, I am in a pinch because I am overwriting the repository of the first Object created with the second, even if it is still "alive". This behavior is undefined.

+1
Apr 02 2018-12-12T00:
source share

I believe that this is a standard for garbage collection. And point out that C ++ behaves differently than some other languages, without causing destructors when compiled.

It specifically states that memory can be reused without invoking object destructors in this memory area. If the program depends on the starting destructors, it will not work properly.

If it does not depend on destructors, everything is in order.

+1
Apr 02 2018-12-12T00:
source share



All Articles