我目前使用 MS 特定的 mm_malloc 为数组分配内存。我对齐内存,因为我正在做一些繁重的数学运算,而矢量化利用了对齐。我想知道是否有人知道如何重载 new 运算符来做同样的事情,因为我觉得到处都是肮脏的 malloc(并且最终也想在 Linux 上编译)?感谢您的帮助
最佳答案
首先,重要的是要注意 new
和 delete
可以全局重载,也可以只为单个类重载。两种情况都显示在 this article 中。 .还需要注意的重要一点是,如果您重载 new
,您几乎肯定还想重载 delete
。
关于 operator new
和 operator delete
有几个重要的注意事项:
- C++ 标准要求返回一个有效的指针,即使传递给它的大小为 0。
- 还有
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++。
关于c++ - 用新的返回对齐的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2660076/