C++ Aligned Array or vector of "unsigned long" on 64-byte boundary, and associated delete[]

Viewed 289

I have tried

unsigned long* ulongsArray = new(std::align_val_t{ 64 }) unsigned long[1024];
delete[] ulongsArray;
// ::operator delete[](ulongsArray, std::align_val_t{ 64 });   // same compiler error
// ::operator delete[](new(std::align_val_t{ 64 }) unsigned long[1024], std::align_val_t{ 64 });   // same compiler error

but, under VisualStudio 2019 get an error "error C2956: usual deallocation function 'void operator delete[](void *,std::align_val_t) noexcept' would be chosen as placement deallocation function." which seems to point to the C++17 standard lacking definition for the delete[] of aligned arrays.

VisualStudio2019 seems to align on 64-byte boundaries by default, along with Intel Compiler. However, g++ seems to align to 16-byte boundaries, and I need 64-byte alignment (cache line).

1 Answers

This appears to be an issue with the MSVC compiler as it compiles fine with gcc and clang. It's been reported in the past here

However, the intended result you are looking for can be achieved (across each of MSVC, clang, and GCC) by doing the following instead:

unsigned long *ulongsArray = static_cast<unsigned long*>(
        operator new[](sizeof(unsigned long) * 64, (std::align_val_t)(64)));
delete[] ulongsArray;
Related