如何对齐结构数组,每个结构都需要对齐(SSE)

How to align array of structs, each require alignment (SSE)

本文关键字:结构 对齐 SSE 数组 何对齐      更新时间:2023-10-16

我有一个struct alignedStruct,它需要特殊对齐(SEE ext):

void* operator new(size_t i) { return _aligned_malloc(i, 16); }
void operator delete(void* p) { _aligned_free(p); }

这种对齐方式适用于alignedStruct的唯一对象/指针,但后来我尝试这样做:

alignedStruct * arr = new alignedStruct[count];

我的应用程序崩溃了,问题肯定是关于"阵列对齐"(正好在前一行):

0xC0000005: Access violation reading location 0xFFFFFFFF.

这样的崩溃发生在约60%的时间内,也表明问题并不典型。

我相信您想要的是放置new,它允许您正确地使用带有构造函数的_aligned_malloc。或者,您可以过载operator new[]operator delete[]

void* operator new[] (std::size_t size)
{
   void * mem = _aligned_malloc(size, 16);
   if(mem == nullptr)
      throw std::bad_alloc;
   return mem;
}