gpt4 book ai didi

c++ - 重载 operator new 而不重载 operator delete

转载 作者:太空宇宙 更新时间:2023-11-04 14:58:08 25 4
gpt4 key购买 nike

大家好

我有下面的简单代码。我为我的类(class)定义了 operator new 而没有 operator delete。根据 valgrind --leak-check=yes PROGRAM_NAME 我有一个不匹配,即我正在使用 new[] 为数组分配,但我正在使用简单的 delete 解除分配 对于非数组。你知道为什么吗?

问候AFG

#include<string>
#include<new>


class CA{
public:
CA(){
std::cout << "*created CA*";
}

~CA(){
std::cout << "*deleted*";
}

void* operator new( std::size_t aSize ){
std::cout << "*MY NEW*";
void* storage = std::malloc( aSize );
if( !storage )
{
std::exception ex;
throw ex;
}
return storage;
}};

int main(int argc, char** argv){
CA* p = new CA();
delete p;
return 0;

==2767== Mismatched free() / delete / delete []==2767==    at 0x4024851: operator delete(void*) (vg_replace_malloc.c:387)==2767==    by 0x80488BD: main (operator_new_test.cpp:54)==2767==  Address 0x42d3028 is 0 bytes inside a block of size 1 alloc'd==2767==    at 0x4024F20: malloc (vg_replace_malloc.c:236)==2767==    by 0x80489A4: CA::operator new(unsigned int) (operator_new_test.cpp:18)==2767==    by 0x804887B: main (operator_new_test.cpp:53)

最佳答案

您的重载运算符 new 使用 malloc,但随后您使用普通的 C++ delete 运算符解除分配。这是一个典型的错误。如果您使用 malloc 分配,则必须始终使用free 释放。如果您使用 new 进行分配,则必须始终使用 delete 解除分配(对于数组,则为 delete[] ).

您需要重载 delete 运算符并让它调用 free()

关于c++ - 重载 operator new 而不重载 operator delete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4059012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com