我有下面的簡單代碼。我沒有操作員刪除,爲我的班級定義了新操作符。 根據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'在失敗時應該拋出'std :: bad_alloc'。 – 2010-10-30 14:12:59
@Steve:如果只有一個人[回答](http://bit.ly/b8gwX3)以一種萬無一失的方式重載全球新人。 :) – 2010-10-30 14:41:07