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