Search code examples
c++c++17memory-alignment

C++ aligned new[]


Overview

When browsing operator new, operator new[] - cppreference.com, it seems we have a number of options for allocating arrays of objects with specific alignment requirements. However, it is not specified how to use them, and I can't seem to find the correct C++ syntax.

Can I somehow make an explicit call to this operator, or will the compiler automatically infer the overload? :

void* operator new[]( std::size_t count, std::align_val_t al );

Looking at Bartek's coding blog, it seems like the compiler will automatically choose an overload based on whether or not the alignment requirement is larger than __STDCPP_DEFAULT_NEW_ALIGNMENT__ (which is usually 16 on 64-bit machines).

Question

Is it possible to manually choose an overload for the new operator in some cases? Sometimes I might want an allocated block to be aligned in a certain way (I assume the alignment to always be a power of 2, and likely larger than 16).

Choice of compiler

I'm probably going to be using GCC and C++ >= 17 for the foreseeable future.


Solution

  • Additional arguments to operator new are passed within parentheses before the type:

    #include <new>
    
    int* allocate() {
        return new (std::align_val_t(16)) int[40]; // 128-bit alignment
        // will call `void* operator new[](size_t, align_val_t)`
    }