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).
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).
I'm probably going to be using GCC and C++ >= 17 for the foreseeable future.
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.
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.
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.
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)`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With