Dynamic Memory Allocation for Over-Aligned Data
Explore how C++17 introduces new memory allocation functions supporting over-aligned data to optimize performance in applications requiring specific memory alignment. Understand the background, usage with alignas, and practical improvements for standard containers and smart pointers, enhancing your memory management skills in modern C++.
We'll cover the following...
Embedded environments, kernel, drivers, game development and other areas might require a non-default alignment for memory allocations. Complying those requirements might improve the performance or satisfy some hardware interface.
Memory Alignment
For example, to perform geometric data processing using SIMD[^simd] instructions, you might need 16-byte or 32-byte alignment for a structure that holds 3D coordinates:
[^simd]: Single Instruction, Multiple Data, for example, SSE2, AVX, see https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions
struct alignas(32) Vec3d { // alignas is available since C++11
double x, y, z;
};
auto pVectors = new Vec3d[1000];
Vec3d holds double fields, and usually, its natural alignment should be 8 bytes. Now, with alignas keyword, we change this alignment to 32. This approach allows the compiler to fit the objects into SIMD ...