Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Class-specific operator new and operator delete: matching aligned overloads

Separate storage management from object lifetime, choose the alignment-aware overloads, and forward the same alignment to the matching global functions.

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

Syntax

#include <cstddef>
#include <new>

struct T {
    static void* operator new(std::size_t bytes);
    static void operator delete(void* ptr) noexcept;

    static void* operator new(std::size_t bytes, std::align_val_t alignment);
    static void operator delete(void* ptr, std::align_val_t alignment) noexcept;
};

new T(...) obtains storage and then initializes an object in it. For a valid non-null pointer, delete p with the non-destroying form shown here destroys the object before releasing its storage. A direct call to operator new does not automatically run a constructor, and a direct call to a non-destroying operator delete does not automatically run a destructor. A destroying operator delete, however, can invoke the destructor in its function body even when called directly.

The term class-specific operator new/operator delete refers to static member functions, even when static is omitted. For a single object, lookup normally starts in the class; declarations found there hide global functions of the same name. The expressions ::new and ::delete bypass class lookup but still initialize or destroy the object. Do not bypass one side of a pair if the other requires a custom allocation mechanism. Arrays use the separate new[] and delete[] forms.

Alignment-aware overloads use std::align_val_t from <new> and are available since C++17. In C++23, if alignof(T) exceeds __STDCPP_DEFAULT_NEW_ALIGNMENT__, new first tries overload resolution with an alignment argument, then retries without it if no match is found, using the same lookup set. At or below that threshold, the order is reversed. Selection among ordinary deallocation functions likewise prefers an overload with or without an alignment parameter according to that threshold.

If the member calls ::operator new(bytes, alignment), release that block with ::operator delete(ptr, alignment) using the same alignment value. The unaligned overload is not a substitute: violating this requirement results in undefined behavior. In the example, allocation failure throws std::bad_alloc before the counter is incremented. If the constructor throws after allocation, the new expression calls a suitable deallocation function if it finds one, then propagates the exception.

outstanding counts blocks allocated through this pair that have not yet been released. It counts neither bytes nor live objects, does not prove memory safety, and is not safe for concurrent updates.

Examples

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

struct alignas(64) Tracked final {
    enum class Error { construction_failed };
    static inline std::size_t outstanding = 0;

    explicit Tracked(bool fail) {
        if (fail) {
            throw Error::construction_failed;
        }
    }

    static void* operator new(std::size_t bytes, std::align_val_t alignment) {
        void* ptr = ::operator new(bytes, alignment);
        ++outstanding;
        return ptr;
    }

    static void operator delete(void* ptr, std::align_val_t alignment) noexcept {
        if (ptr != nullptr) {
            ::operator delete(ptr, alignment);
            --outstanding;
        }
    }
};

static_assert(alignof(Tracked) > __STDCPP_DEFAULT_NEW_ALIGNMENT__);

int main() {
    auto* ptr = new Tracked(false);
    std::printf("After new: %zu\n", Tracked::outstanding);
    delete ptr;
    std::printf("After delete: %zu\n", Tracked::outstanding);

    try {
        auto* unexpected = new Tracked(true);
        delete unexpected;
        return 1;
    } catch (Tracked::Error) {
        std::printf("After constructor throws: %zu\n", Tracked::outstanding);
    }
}

Result

After new: 1
After delete: 0
After constructor throws: 0

The example requires support for `alignas(64)` and a passing static assertion confirming that the default threshold is exceeded. If both allocations succeed, `1` means one outstanding block; the two `0` values show cleanup by `delete` and cleanup after a constructor exception, respectively.

Related lessons

  • C++ · Lesson 20 · Advanced · Version: 3

Sources