Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Is it UB to re-use an object's storage without destroying it first?

Given non-POD type T:

auto p = new T();
::new (p) T();
/* ... */
delete p;

This is UB, right?

Clearly I'm not directly leaking the memory allocated for that first T (and if it has no indirect members then I'm not leaking anything at all), but it never got destructed, which seems to me to be a great candidate for spontaneous annihilation of galaxies populated by sentient cat-like beings.

Thanks to @Xeo for, um, "inspiring" this question in the C++ Lounge.

Upvotes: 16

Views: 439

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

It rather depends.

[C++11: 3.8/1]: The lifetime of an object of type T ends when:

  • if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
  • the storage which the object occupies is reused or released.

Clearly, this is a case of re-use.

And:

[C++11: 3.8/4]: A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, 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.

So, even for a non-POD type T, it's valid iff nothing in your program actually relied on what the destructor was doing.

It's a bit airy-fairy, but it does potentially allow what you're doing.


Note that this leniency does not extend to some only slightly more bizarre cases:

[C++11: 3.8/9]: Creating a new object at the storage location that a const object with static, thread, or automatic storage duration occupies or, at the storage location that such a const object used to occupy before its lifetime ended results in undefined behavior

Upvotes: 21

Related Questions