C++ over-aligned memory allocation
#include <cstdio> #include <cstdlib> #include <new> struct S{ char buff[10]; }; int main() { S* p1 = new S; std::printf("default-aligned address: %p\n", static_cast<void*>(p1)); S* p2 = new (std::align_val_t{32}) S; std::printf("over-aligned address: %p\n", static_cast<void*>(p2)); }
new运算符支持指定按什么对齐了。over-aligned意思是超过默认的对齐的尺寸。std::max_align_t是个类型,其对齐大小为标量当中最大的那个
#include <new> #include <iostream> int main() { std::cout << alignof(std::max_align_t) << '\n'; }
经测试,MS上的值为8。其它平台的典型值为8或16。
参考:https://ask.helplib.com/others/post_12363048
http://en.cppreference.com/w/cpp/memory/new/operator_new