我试着让全球超载
new
delete
我的程序的操作员:
标题
void* operator new(std::size_t n);
void* operator new(std::size_t n, const std::nothrow_t&);
void operator delete(void* p);
void* allocMemory(std::size_t n) {
MemoryAllocationRecord** pRecord = static_cast<MemoryAllocationRecord**>(
malloc(n + sizeof(MemoryAllocationRecord*)));
if(pRecord == nullptr) return nullptr;
void* retBlock = static_cast<void*>(pRecord+1);
*pRecord = nullptr;
//may set *pRecord to a legal pointer
return retBlock;
}
void* operator new(std::size_t n) {
void* ret = allocMemory(n);
if(ret == nullptr) throw std::bad_alloc();
return ret;
}
void* operator new(std::size_t n, const std::nothrow_t&) {
return allocMemory(n);
}
void operator delete(void* p) {
if(p == nullptr) return;
MemoryAllocationRecord** pRecord = static_cast<MemoryAllocationRecord**>(p) - 1;
if(*pRecord != nullptr){
//may use *pRecord as a legal pointer
}
return free(pRecord);
}
当我在一个应用程序(它使用Qt 5.11库)中使用它时,它可以正常工作。但在另一个应用程序中,库类型的析构函数(
QList<QVariant>
删除
记忆是这样的:
2a 38 02 00 fd fd fd fd*3c 28 5b 00 ...
*
pRecord == 0xfdfdfdfd0002382a
(然后它自然会崩溃)。很明显
fdfdfdfd
如果有任何问题,编译器是MSVC 2017,64位二进制,OS是Windows 7,文件中包含带有运算符重载的头
QList<QVariant>