Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::align_val_t — the memory-alignment argument type

std::align_val_t from <new> carries a required alignment to allocation and deallocation overloads. It is a distinct enumeration type that lets overloads distinguish an alignment argument from a storage-size argument.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <new>
// Declaration in namespace std:
enum class align_val_t : size_t {};

// Explicit aligned allocation and matching deallocation:
void* p = ::operator new(sizeof(T), std::align_val_t{alignof(T)});
::operator delete(p, std::align_val_t{alignof(T)});

std::align_val_t is a scoped enumeration declared in <new>, with no named enumerators and underlying type std::size_t. A value such as std::align_val_t{alignof(T)} carries the required alignment in bytes, not the allocation size. Its distinct type differentiates overloads accepting alignment from those accepting size.

For new T when the type's alignment exceeds __STDCPP_DEFAULT_NEW_ALIGNMENT__, allocation-function selection first considers an alignment argument of type std::align_val_t. Custom class-specific overloads can affect selection; ordinary code does not need to pass this argument manually.

Calling ::operator new(size, alignment) directly allocates storage but does not invoke a constructor for T. Release that storage with the matching ::operator delete(ptr, alignment), passing the same alignment value. Do not mix these functions with free, ordinary unaligned deallocation, or array forms. In C++23, releasing dynamically allocated storage can end an object's lifetime without calling its destructor, even if that destructor is non-trivial. Releasing the storage does not call the destructor implicitly, so its cleanup and other side effects are skipped.

Converting to std::align_val_t does not validate alignment: passing an invalid value to allocation or deallocation functions causes undefined behavior. Use alignof(T) rather than guessing supported values. In the example, placement new initializes an int, the result is copied, and storage is released before printing. int needs no explicit destructor call.

Examples

#include <iostream>
#include <new>

int main() {
    constexpr auto alignment = std::align_val_t{alignof(int)};
    void* storage = ::operator new(sizeof(int), alignment);
    int* value = ::new (storage) int{42};
    const int result = *value;
    ::operator delete(storage, alignment);
    std::cout << result << '\n';
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources