C++ 对齐 new[]
C++ aligned new[]
概览
浏览 operator new, operator new[] - cppreference.com 时,我们似乎有许多选项可以分配具有特定对齐要求的对象数组。但是,没有指定如何使用它们,而且我似乎找不到正确的 C++ 语法。
我能否以某种方式显式调用此运算符,或者编译器会自动推断重载? :
void* operator new[]( std::size_t count, std::align_val_t al );
查看Bartek's coding blog,似乎编译器会根据对齐要求是否大于__STDCPP_DEFAULT_NEW_ALIGNMENT__
(在64位机器上通常为16)自动选择重载.
问题
在某些情况下是否可以手动为 new
运算符选择重载?有时我可能希望分配的块以某种方式对齐(我假设对齐始终是 2 的幂,并且可能大于 16)。
编译器的选择
在可预见的未来,我可能会使用 GCC 和 C++ >= 17。
operator new
的附加参数在类型前的括号内传递:
#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)`
}
概览
浏览 operator new, operator new[] - cppreference.com 时,我们似乎有许多选项可以分配具有特定对齐要求的对象数组。但是,没有指定如何使用它们,而且我似乎找不到正确的 C++ 语法。
我能否以某种方式显式调用此运算符,或者编译器会自动推断重载? :
void* operator new[]( std::size_t count, std::align_val_t al );
查看Bartek's coding blog,似乎编译器会根据对齐要求是否大于__STDCPP_DEFAULT_NEW_ALIGNMENT__
(在64位机器上通常为16)自动选择重载.
问题
在某些情况下是否可以手动为 new
运算符选择重载?有时我可能希望分配的块以某种方式对齐(我假设对齐始终是 2 的幂,并且可能大于 16)。
编译器的选择
在可预见的未来,我可能会使用 GCC 和 C++ >= 17。
operator new
的附加参数在类型前的括号内传递:
#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)`
}