【发布时间】:2016-06-20 07:57:14
【问题描述】:
我想修改一个数组分配:
float * a = new float[n] ;
使用对齐的分配器。我倾向于尝试使用placement new 和posix_memalign(或新的c++11 等效项),但请参阅placement new with arrays is problematic with array allocations,因为compiler may need to have additional storage for count or other metadata。
我试过了:
int main()
{
float * a = new alignas(16) float[3] ;
a[2] = 0.0 ;
return a[2] ;
}
但编译器似乎表明忽略了对齐:
$ g++ -std=c++11 t.cc -Werror
t.cc: In function ‘int main()’:
t.cc:4:39: error: attribute ignored [-Werror=attributes]
float * a = new alignas(16) float[3] ;
^
t.cc:4:39: note: an attribute that appertains to a type-specifier is ignored
看起来使用 alignas 的正确方法是在 structure declaration declare a structure with alignas 中,但这仅适用于固定大小。
还有一个aligned_storage 模板,但我认为它也只适用于固定大小。
是否有任何标准方法来执行对齐数组分配,将调用所有元素的构造函数?
【问题讨论】: