对一个void*类型指针进行delete操作会出错,除非指针所指的内容是简单类型内容,因为这个操作只会释放内存,而不会执行析构函数
下面是一个代码示例:
//:BadVoidPointerDeletion.cpp #include <iostream> using namespace std; class Object { void* data; // Some storage const int size; const char id; public: Object(int sz, char c) : size(sz), id(c) { data = new char[size]; cout << "Constructing object " << id << ", size = " << size << endl; } ~Object() { cout << "Destructing object " << id << endl; delete []data; // OK, just releases storage, // no destructor calls are necessary } }; int main() { Object* a = new Object(40, 'a'); delete a; void* b = new Object(40, 'b'); delete b; //会释放Object对象的内存,但不会释放data所指向的内存,即不会执行析构函数 }
运行结果:
Constructing object a, size = 40
Destructing object a
Constructing object b, size = 40
如果在程序中发现了内存丢失,应该搜索所有的delete语句并检查被删除指针的类型,
如果是void*类型,则可能发现了引起内存丢失的某个原因。