Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Placement new: construction in existing storage

Construct an object in a prepared slot, manage its lifetime separately from the storage, and make the slot owner explicitly non-copyable and non-movable.

Version: ISO C++23; implementation support may vary

Syntax

#include <new>

// Assumes overload resolution selects the standard non-allocating placement overload.
T* p = ::new (static_cast<void*>(storage)) T(args...);  // Construct one T in existing storage.
p->~T();                                              // Destroy that T without freeing the storage.

// Inside the owning class, disable copying and moving:
Owner(const Owner&) = delete;
Owner& operator=(const Owner&) = delete;
Owner(Owner&&) = delete;
Owner& operator=(Owner&&) = delete;

In C++23, ::new (static_cast<void*>(storage)) T(args...) constructs a T at the supplied address and returns T* when it selects the standard non-allocating operator new(std::size_t, void*) from <new>. That global overload just returns the address. The leading :: bypasses class-scope lookup, but the cast to void* does not guarantee selection of the standard overload. If alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__, overload resolution first includes an extra std::align_val_t argument, so a viable global alignment-aware placement overload can be selected instead. If no matching allocation function is found on that pass, overload resolution is retried without the alignment argument. Ordinary allocating new T(args...) obtains storage and initializes the object. Other placement overloads can allocate.

Supply a valid, non-null address, at least sizeof(T) available bytes, and alignment that satisfies alignof(T). The example uses alignas(Item) for alignment. The constructed object's lifetime begins after successful initialization. If the constructor throws, the matching standard placement operator delete(void*, void*) does not free anything. Mark the slot occupied only after construction succeeds.

Keep the T* returned by the new-expression. A cast alone does not construct the object, and a matching address does not authorize access through an incompatible type (strict aliasing). std::launder can obtain a pointer to an already-live object of a similar type at that address if the byte-reachability requirement is met. It neither starts a lifetime nor fixes alignment. It is not needed here.

The explicit destructor call p->~T() destroys the object without releasing arena or buffer storage. In this pattern, destroy each successfully constructed object exactly once before reusing the slot or letting the buffer go away. Do not use delete p on an object in this buffer: a delete-expression paired with an appropriate allocating new-expression normally destroys the object and deallocates the storage.

= delete defines a deleted function; it is not a delete-expression. The function still participates in overload resolution, but a call that selects it is ill-formed. Slot deletes the copy and move constructors and both corresponding assignment operators. Default memberwise copying would copy the pointer into the source buffer without constructing an Item in the destination buffer.

Examples

#include <cstddef>
#include <cstdio>
#include <new>

struct Item {
    int value;
    explicit Item(int n) : value(n) {}
    ~Item() { std::puts("destroyed"); }
};

class Slot {
    alignas(Item) std::byte storage_[sizeof(Item)];
    Item* item_ = nullptr;

public:
    Slot() = default;
    ~Slot() { reset(); }

    Slot(const Slot&) = delete;
    Slot& operator=(const Slot&) = delete;
    Slot(Slot&&) = delete;
    Slot& operator=(Slot&&) = delete;

    Item& emplace(int n) {
        reset();
        item_ = ::new (static_cast<void*>(storage_)) Item(n);
        return *item_;
    }

    void reset() noexcept {
        if (item_) {
            item_->~Item();
            item_ = nullptr;
        }
    }
};

int main() {
    Slot slot;
    std::printf("%d\n", slot.emplace(7).value);
    std::printf("%d\n", slot.emplace(9).value);
}

Result

7
destroyed
9
destroyed

The second `emplace` destroys the `Item` holding `7` before constructing `9` in the same buffer. The `Slot` destructor destroys the second object.

Related lessons

  • C++ · Lesson 16 · Advanced · Version: 3
  • C++ · Lesson 19 · Advanced · Version: 3

Sources