c++ - 用新的返回对齐的内存?

标签 c++ alignment

我目前使用 MS 特定的 mm_malloc 为数组分配内存。我对齐内存,因为我正在做一些繁重的数学运算,而矢量化利用了对齐。我想知道是否有人知道如何重载 new 运算符来做同样的事情,因为我觉得到处都是肮脏的 malloc(并且最终也想在 Linux 上编译)?感谢您的帮助

最佳答案

首先,重要的是要注意 newdelete 可以全局重载,也可以只为单个类重载。两种情况都显示在 this article 中。 .还需要注意的重要一点是,如果您重载 new,您几乎肯定还想重载 delete

关于 operator newoperator 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;
}

要了解更多信息,我肯定会选择 Effective C++

关于c++ - 用新的返回对齐的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2660076/

相关文章:

c++ - 如何在 3D 中对 QML 旋转变换进行动画处理和属性插值

c++ - 在 Visual Studio 2010 中使用 'auto' 关键字的性能损失

c# - 如何在 RichTextBox C# 中处理 'align' 文本?

CSS Div 对齐形式

c++ - 将正在运行的应用程序中的共享对象热更新到 Linux 上的新版本

c++ - &C::c 和 &(C::c) 有什么区别?

c++ - 使用用户输入的字符创建梯形。 (控制台应用程序)

html - 如何垂直对齐字形?

css -- 在居中元素的左侧放置一些东西?

python - 在python中对齐DNA序列