Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Removed links to recs and made minor editorial changes

The creation of dynamically allocated objects in C++ happens in two stages. The first stage is responsible for allocating sufficient memory to store the object, and the second stage is responsible for initializing the newly allocated chunk of memory, depending on the type of the object being created.

Similarly, the destruction of dynamically allocated objects in C++ happens in two stages. The first stage is responsible for finalizing the object, depending on the type, and the second stage is responsible for deallocating the memory used by the object. The C++ Standard, [basic.life], paragraph 1 [ISO/IEC 14882-2014], states the following:

The lifetime of an object is a runtime property of the object. An object is said to have non-trivial initialization if it is of a class or aggregate type and it or one of its members is initialized by a constructor other than a trivial default constructor. [Note: initialization by a trivial copy/move constructor is non-trivial initialization. — end note] The lifetime of an object of type T begins when:

— storage with the proper alignment and size for type T is obtained, and
— if the object has non-trivial initialization, its initialization is complete.

The lifetime of an object of type T ends when:

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

...

When a program creates a dynamically allocated object by means other than the new operator, it is said to be manually managing the lifetime of that object. This situation arises when using other allocation schemes to obtain storage for the dynamically allocated object, such as using an allocator object or malloc(). For example, a custom container class may allocate a slab of memory in a reserve() function in which subsequent objects will be stored. See MEM51-CPP. Properly deallocate dynamically allocated resources for further information on dynamic memory management as well as MEM08-CPP. Use new and delete rather than raw memory allocation and deallocation.

When manually managing the lifetime of an object, the constructor must be called to initiate the lifetime of the object. Similarly, the destructor must be called to terminate the lifetime of the object. Use of an object outside of its lifetime is undefined behavior. An object can be constructed either by calling the constructor explicitly using the placement new operator or by calling the construct() function of an allocator object. An object can be destroyed either by calling the destructor explicitly or by calling the destroy() function of an allocator object.

...

In this noncompliant code example, a custom container class uses an allocator object to obtain storage for arbitrary element types. While the copy_elements() function is presumed to call copy constructors for elements being moved into the newly - allocated storage, this example fails to explicitly call the default constructor for any additional elements being reserved. If such an element is accessed through the operator[]() function, it results in undefined behavior, depending on the type T.

...

In this compliant solution, all elements are properly initialized by explicitly calling copy or default constructors for T:.

Code Block
bgColor#ccccff
langcpp
#include <memory>

template <typename T, typename Alloc = std::allocator<T>>
class Container {
  T *underlyingStorage;
  size_t numElements;
  
  void copy_elements(T *from, T *to, size_t count);
  
public:
  void reserve(size_t count) {
    if (count > numElements) {
      Alloc alloc;
      T *p = alloc.allocate(count); // Throws on failure
      try {
        copy_elements(underlyingStorage, p, numElements);
        for (size_t i = numElements; i < count; ++i) {
          alloc.construct(&p[i]);
        }
      } catch (...) {
        alloc.deallocate(p, count);
        throw;
      }
      underlyingStorage = p;
    }
    numElements = count;
  }
  
  T &operator[](size_t idx) { return underlyingStorage[idx]; }
  const T &operator[](size_t idx) const { return underlyingStorage[idx]; }
};

...

Bibliography

[ISO/IEC 14882-2014]Subclause 3.8, "Object Lifetime"
Clause 9, "Classes"

...