用新的回归对齐的记忆?

时间:2010-04-17 21:05:13

标签: c++ alignment

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

2 个答案:

答案 0 :(得分:10)

首先,重要的是要注意newdelete可以全局重载,或仅针对单个类重载。这两种情况都显示在this article中。另外需要注意的是,如果你重载new,你几乎肯定也想要重载delete

有一些关于operator newoperator delete的重要说明:

  1. C ++标准要求返回有效指针,即使传递给它的大小为0。
  2. 还有operator new[]operator delete[],所以不要忘记重载这些内容。
  3. 派生类会继承operator new及其兄弟,所以请务必覆盖它们。
  4. 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;
    }
    

    有关详细信息,我肯定会选择 Effective C ++

答案 1 :(得分:2)

new需要返回pointer [...] suitably aligned so that it can be converted to a pointer of any complete object type(标准的§3.7.3.1)。

FWIW,C ++ 0x将添加alignof,它将告诉您特定类型所需的对齐方式。