delete void pointer是否会有内存泄漏?
看下面一个简单例子
class Test{
public:
Test(){
printf ("constructor\n");
}
~Test(){
printf("destructor");
}
};
int main(int argc, char *argv[])
{
Test *p = new Test();
void *p1 = p;
delete p1;
printf("the end\n");
getchar();
return 0;
}
结果输出:
从输出可以看出来,没有调用类的析构函数;
网上解释:
It depends on "safe." It will usually work because information is stored along with the pointer about the allocation itself, so the deallocator can return it to the right place. In this sense it is "safe" as long as your allocator uses internal boundary tags. (Many do.)
However, as mentioned above, deleting a void pointer will not call destructors, which can be a problem. In that sense, it is not "safe."
参考:http://stackoverflow.com/questions/941832/is-it-safe-to-delete-a-void-pointer