2010-10-30 123 views
0

嗨全部超载运营商新,没有超载运营商删除

我有下面的简单代码。我没有操作员删除,为我的班级定义了新操作符。 根据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) 
+1

与这个问题无关,但'new'在失败时应该抛出'std :: bad_alloc'。 – 2010-10-30 14:12:59

+0

@Steve:如果只有一个人[回答](http://bit.ly/b8gwX3)以一种万无一失的方式重载全球新人。 :) – 2010-10-30 14:41:07

回答

0

如果用malloc分配你应该free释放。

8

你重载操作new使用malloc,但随后取消分配使用普通的C++ delete运营商。这是一个经典错误。如果您使用malloc进行分配,则必须使用总是free取消分配。如果使用new进行分配,则必须始终使用delete(或在数组的情况下为delete[])进行分配。

您需要超载delete运营商并让其拨打free()

+1

+1 - 你有没有觉得我们都会解释这个,直到我们非常非常老? – bgporter 2010-10-30 14:07:48

+1

有一天,我会给我的孙子们提供一些关于生命的重要建议:不要混合使用'malloc'和'new',否则有一天你会后悔的。 – 2010-10-30 14:14:40

+0

我通常使用pair new/delete和new []/delete []。我虽然这是因为malloc在新的使用这个将被掩盖了一些,所以在我的头看起来像一个普通的新/删除对。非常感谢您的好评! – 2010-10-31 16:22:42

1

当你重载operator new时,你的必须重载operator operator delete这样你才知道正确的deallocation函数(在这种情况下是free的)被调用。

您的超负荷还存在一些问题;见my example on overloading new。只需用malloc和deallocate_from_some_other_source替换allocate_from_some_other_source即可。