Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 853
alexpanter Avatar asked Oct 28 '20 20:10

alexpanter


People also ask

What is align in C?

One of the low-level features of C is the ability to specify the precise alignment of objects in memory to take maximum advantage of the hardware architecture. CPUs read and write memory more efficiently when they store data at an address that's a multiple of the data size.

What is :: operator new?

The new operator invokes the function operator new . For arrays of any type, and for objects that aren't class , struct , or union types, a global function, ::operator new , is called to allocate storage. Class-type objects can define their own operator new static member function on a per-class basis.

What is new operator C++?

The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.


1 Answers

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)`
}
like image 180
Fatih BAKIR Avatar answered Oct 20 '22 10:10

Fatih BAKIR