2010-10-30 121 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即可。