我目前使用MS特定的mm_malloc为阵列分配内存。我调整了内存,因为我正在做一些重型数学运算,矢量化利用了对齐。我想知道是否有人知道如何重载新操作符来做同样的事情,因为我觉得到处都是脏的malloc'ing(最终还想在Linux上编译)?谢谢你的帮助
答案 0 :(得分:10)
首先,重要的是要注意new
和delete
可以全局重载,或仅针对单个类重载。这两种情况都显示在this article中。另外需要注意的是,如果你重载new
,你几乎肯定也想要重载delete
。
有一些关于operator new
和operator delete
的重要说明:
operator new[]
和operator delete[]
,所以不要忘记重载这些内容。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 ++ 。
答案 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
,它将告诉您特定类型所需的对齐方式。