Géry Ogam
Géry Ogam

Reputation: 8027

Does storage reuse really require object destruction?

According to [basic.life/1] (bold emphasis mine):

The lifetime of an object of type T begins when:

  • storage with the proper alignment and size for type T is obtained, and
  • its initialization (if any) is complete (including vacuous initialization) ([dcl.init]), except that if the object is a union member or subobject thereof, its lifetime only begins if that union member is the initialized member in the union ([dcl.init.aggr], [class.base.init]), or as described in [class.union] and [class.copy.ctor], and except as described in [allocator.members].

The lifetime of an object o of type T ends when:

  • if T is a non-class type, the object is destroyed, or
  • if T is a class type, the destructor call starts, or
  • the storage which the object occupies is released, or is reused by an object that is not nested within o ([intro.object]).

So we have:

|------------|----|--------------|----------|-------------|----|--------------|

 <---------->      <------------> <--------> <----------->      <------------>
  storage           object         object     object             storage
  allocation        construction   lifetime   destruction        deallocation

              <----------------------------------------------->
               storage duration

According to [basic.life/8] (bold emphasis mine):

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if the original object is transparently replaceable (see below) by the new object.

Two questions come to mind:

  1. Is the placement new operator the only means to reuse storage?
  2. Does the consequence specified in [basic.life/8] really require the original object to be destroyed (i.e. the condition ‘after the lifetime of an object has ended’)?

Upvotes: 1

Views: 142

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473352

As you quoted, if you reuse storage for a new object, the old object(s) in that storage have their lifetimes ended (unless the new object is nested within the old one). So if you create a new object inside storage containing an existing object(s), then the existing object(s) won't exist anymore.

Is the placement new operator the only means to reuse storage?

The word "reuse" is not a term of art; it's just English. Anything that creates an object in storage will "reuse" the storage. For example, construct_at can reuse storage too.

Upvotes: 0

Related Questions