归国对齐的内存与新? [英] returning aligned memory with new?

查看:128
本文介绍了归国对齐的内存与新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我分配我的记忆中使用的MS具体mm_malloc阵列。我对齐的记忆,因为我正在做一些重型数学和矢量拍摄校准的优势。我想知道是否有人知道如何重载新的运营商做同样的事情,因为我觉得脏malloc'ing无处不在(并最终想也编译在Linux上)?感谢您的帮助

I currently allocate my memory for arrays using the MS specific mm_malloc. I align the memory, as I'm doing some heavy duty math and the vectorization takes advantage of the alignment. I was wondering if anyone knows how to overload the new operator to do the same thing, as I feel dirty malloc'ing everywhere (and would eventually like to also compile on Linux)? Thanks for any help

推荐答案

首先,需要注意的是删除<非常重要/ code>可以被重载无论是在全球范围,或只是一个类。这两种情况都显示在这篇文章。另外需要注意的是,如果你超载你几乎肯定要超载删除

First of all, it's important to note that new and delete can be overloaded either globally, or just for a single class. Both cases are shown in this article. Also important to note is that if you overload new you almost certainly also want to overload delete.

有大约几个重要事项运营商新的的operator delete

There are a few important notes about operator new and operator delete:

  1. 在C ++标准要求,即使传递给它的大小为0的有效指针的值。
  2. 还有运营商新的[] 的operator delete [] ,所以不要忘了超载的。
  3. 在派生类继承运营商新的和它的兄弟们,所以一定要覆盖这些。
  1. The C++ standard requires that a valid pointer is returned even if the size passed to it is 0.
  2. There's also operator new[] and operator delete[], so don't forget about overloading those.
  3. Derived classes inherit operator new and its brethren, so make sure to override those.

C ++有效的,第8项,斯科特迈尔斯包括一些pseudocodish例子:

In Effective C++, item 8, Scott Meyers includes some pseudocodish examples:

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;
}

有关详细信息,我肯定会拿起的 C ++有效的。

For more information, I'd definitely pick up Effective C++.

这篇关于归国对齐的内存与新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆