Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call the overloaded aligned new and delete operators in `C++17`?

From cppreference we can see several new overloads of new and delete, as well as new[] and delete[] were added. I can't find any examples of usage with the new aligned overloads, neither on cppreference nor anywhere else. I've experimented with them for quite some time now and I can't find out how to trigger these aligned dynamically allocated calls. Anyone has any idea, kindly share an example.

like image 935
KeyC0de Avatar asked Jan 28 '23 05:01

KeyC0de


1 Answers

You need to specify the align as keyword on your type and then just call new and delete as normal. I have put together an article with examples about it here: https://github.com/Twon/Alignment/blob/master/docs/alignment_in_C%2B%2B.md. An example is:

#include <memory>

int main() {
    class alignas(16) float4 {
        float f[4];
    }; 

    std::unique_ptr<float4 > aligned_vec4(std::make_unique<float4 >());
}

And an example with the Intel compiler which currently make this feature available via the aligned_new extension header: https://software.intel.com/en-us/articles/aligned-operator-new-support-in-intel-c-compiler

like image 151
Antony Peacock Avatar answered Feb 16 '23 04:02

Antony Peacock