Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why exactly is calling the destructor for the second time undefined behavior in C++?

As mentioned in this answer simply calling the destructor for the second time is already undefined behavior 12.4/14(3.8).

For example:

class Class {
public:
    ~Class() {}
};
// somewhere in code:
{
    Class* object = new Class();
    object->~Class();
    delete object; // UB because at this point the destructor call is attempted again
}

In this example the class is designed in such a way that the destructor could be called multiple times - no things like double-deletion can happen. The memory is still allocated at the point where delete is called - the first destructor call doesn't call the ::operator delete() to release memory.

For example, in Visual C++ 9 the above code looks working. Even C++ definition of UB doesn't directly prohibit things qualified as UB from working. So for the code above to break some implementation and/or platform specifics are required.

Why exactly would the above code break and under what conditions?

like image 245
sharptooth Avatar asked May 05 '10 08:05

sharptooth


People also ask

Why is destructor being called twice?

The constructor code is the construction of t1. Then a copy constructor is used when it is pushed back on the vector. When the clear() is called, it calls the destructor for the object in the vector. Then t1's destructor is called when it goes out of scope.

How many times a destructor can be called?

Why is the destructor being called three times?

Is destructor called after return?

However, in your current implementation you're actually returning a shallow copy of NodeContainer. Once your copy goes out of scope its destructor is called, which deallocates its memory, which in this case is the original memory of your member, effectively making your member invalid.

Does the destructor automatically get called?

A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .


1 Answers

I think your question aims at the rationale behind the standard. Think about it the other way around:

  1. Defining the behavior of calling a destructor twice creates work, possibly a lot of work.
  2. Your example only shows that in some trivial cases it wouldn't be a problem to call the destructor twice. That's true but not very interesting.
  3. You did not give a convincing use-case (and I doubt you can) when calling the destructor twice is in any way a good idea / makes code easier / makes the language more powerful / cleans up semantics / or anything else.

So why again should this not cause undefined behavior?

like image 74
Sebastian Avatar answered Oct 14 '22 23:10

Sebastian