用新的回归对齐的记忆?

Ste*_*eve 8 c++ alignment

我目前使用MS特定的mm_malloc为阵列分配内存.我调整了内存,因为我正在做一些重型数学运算,矢量化利用了对齐.我想知道是否有人知道如何重载新操作符来做同样的事情,因为我觉得到处都是脏的malloc'ing(最终还想在Linux上编译)?谢谢你的帮助

rlb*_*ond 10

首先,重要的是要注意new并且delete可以在全局或仅针对单个类重载.这两种情况都显示在本文中.另外需要注意的是,如果你超负荷,new你几乎肯定也想超载delete.

关于operator new和,有一些重要的注意事项operator delete:

  1. C++标准要求返回有效指针,即使传递给它的大小为0.
  2. 还有operator new[]operator delete[],所以不要忘了那些超载.
  3. 派生类继承operator new及其兄弟,所以一定要覆盖它们.

Effective C++,第8项中,Scott Meyers包含一些伪编码示例:

void * operator new(size_t size)        // your operator new might
{                                       // take additional params
  if (size == 0) {                      // handle 0-byte requests
    size = 1;                           // by treating them as
  }                                     // 1-byte requests
  while (1) {
    attempt to allocate size bytes;
    if (the allocation was successful)
      return (a pointer to the memory);

    // allocation was unsuccessful; find out what the
    // current error-handling function is (see Item 7)
    new_handler globalHandler = set_new_handler(0);
    set_new_handler(globalHandler);

    if (globalHandler) (*globalHandler)();
    else throw std::bad_alloc();
  }
}


void operator delete(void *rawMemory)
{
  if (rawMemory == 0) return;    // do nothing if the null
                                 // pointer is being deleted
  deallocate the memory pointed to by rawMemory;
  return;
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,我肯定会选择Effective C++.