乐闻世界logo
搜索文章和话题

Is it safe to delete a void pointer?

1个答案

1

Deleting a null pointer in C++ is safe. Per the C++ standard, delete p first checks if p is nullptr; if it is, delete performs no operation.

Why is this designed this way?

This design enhances safety and convenience. Developers may sometimes forget whether a pointer has been released, or in complex programs, pointers might already be set to nullptr. This rule is highly beneficial as it prevents program crashes caused by attempting to delete a pointer that is already nullptr.

Example

Suppose we have a simple class Cat, where we create a pointer to a Cat object and release it when no longer needed:

cpp
class Cat { public: Cat() { cout << "Cat created." << endl; } ~Cat() { cout << "Cat destroyed." << endl; } }; int main() { Cat* myCat = new Cat(); // Dynamic memory allocation delete myCat; // Memory deallocation myCat = nullptr; // Set pointer to nullptr // Double deletion test delete myCat; // This is safe because myCat is nullptr return 0; }

In this example, attempting to delete the myCat pointer a second time (which is now nullptr) is safe because the C++ standard library's delete operation first checks if the pointer is nullptr.

Important Notes

While deleting a null pointer is safe, it is good practice to set the pointer to nullptr immediately after deletion. This prevents dangling pointer issues, where the pointer still references deallocated memory. Setting it to nullptr ensures subsequent deletions are safe and helps identify uninitialized pointer usage during debugging.

2024年6月29日 12:07 回复

你的答案