#include <stdlib.h>
#include <stdio.h>
void *malloc(int size)
{
printf("my malloc called!\n");
}
void free(void* ptr)
{
printf("my free called!\n");
}
void* operator new[](size_t s)
{
printf("my new[] called!\n");
return 0;
}
void operator delete[](void* p)
{
printf("my delete[] called!\n");
}
void * operator new(size_t s)
{
printf("my new called!\n");
return 0;
}
void operator delete(void* p)
{
printf("my delete called!\n");
}
int main()
{
int *a = (int *)malloc(4);
free(a);
int *c = new int[3];
delete[] c;
delete[] c;
char *b = new char;
delete b;
}
代码非常简单就是重载了new delete new[] delete[]这几个运算符,但是运行后结果显示:
my malloc called!
my free called!
my new[] called!
my new called!
my delete called!
new delete new[]能够成功重载delete[]却重载失败,依然调用系统的delete[]请问各位大侠,我到底哪里出了问题,谢谢!
delete c
------解决方案--------------------------------------------------------
试试这个,看看能否正常调用。
ps. 在我这里可以的。
#include <cstddef>
#include <cstdio>
void* operator new [] (size_t s)
{
printf("my new[] called!\n");
return operator new(s);
}
void operator delete [] (void* ptr) throw ()
{
printf("my delete[] called!\n");
operator delete (ptr);
}
int main ()
{
int *c = new int[3];
delete [] c;
return 0;
}
------解决方案--------------------------------------------------------
测试了一下,原因是你重载的new返回了0,int *c = new int[3];这步过后c的地址实际是NULL,而delete碰到NULL是可以什么都不做的,至于为什么非数组的delete仍然被调用,我就不清楚了
------解决方案--------------------------------------------------------
猜测:你的new返回0,这样c的值就是0。而C++规定delete一个零指针时什么也不做。
delete[]版本需要先确定数组大小,这时己发现指针为0,于是直接跳过后续步骤。
你应当像2楼一样返回一个有意义的值,而不是0
------解决方案--------------------------------------------------------
我觉得这是编译器实现过分解读标准造成的 bug, c++11 3.7.4.2/3 说
... The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. ...
注意 delete ?; 无动作的要求受两个条件控制,
(1) ? == 0;
(2) operator delete [] 是库本身提供的,即非用户自定义的。
主楼的例子中 (2) 不满足,因此不能得出 delete 0; 无动作的要求。显然此编译器实现过分解读了标准的要求。