Alex Rivera | Logout

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

Asked 2012-04-02T06:04:15.137
10

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?

Edit
Report

1 Answer

1

Your question does not make sense.

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

They are skipped, because they would have been triggered by the destructor and it has not been called.

My reading of:

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

is simple, I view it in 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 allocate a Manager, forgets to destroy it, and allocates a new one, I am in a pinch for I am overwriting the storage of the first created Object with a second one even though it is still "alive". This is undefined behavior.

answered 2012-04-02T06:31:37.993

Your Answer