Deleting a pointer
In C++, whats the recommended way of deleting a pointer? For example, in the following case, do I need all three lines to delete the pointer safely (and if so, what do they do)?
// Create
MyClass* myObject;
myObject = new MyClass(myVarA, myVarB, myVarC);
// Use
// ...
// Delete
if(myObject) {
delete myOb开发者_StackOverflow中文版ject;
myObject = NULL;
}
No you do not need to check for NULL
.
delete
takes care if the pointer being passed is NULL
.
delete myObject;
myObject = NULL;
is sufficient.
As a general policy, avoid using freestore allocations wherever you can, and if you must use Smart Pointers(RAII) instead of raw pointers.
C++03 Standard Section §3.7.3.2.3:
The value of the first argument supplied to one of the deallocation functions provided in the standard library may be a null pointer value; if so, the call to the deallocation function has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(size_t) or operator new(size_t, const std::nothrow_t&) in the standard library, and the value supplied to operator delete in the standard library shall be one of the values returned by a previous invocation of either operator new or operator new[](size_t, const std::nothrow_t&) in the standard library.
No, you don't need that.
Just write delete p
, and be sure to not accept advice about anything else from anyone advocating that you do more.
General advice: avoid raw new
and delete
. Let some standard container deal with allocation, copying and deallocation. Or use a smart-pointer.
Cheers & hth.,
Best to use a resource-managing class and let the library take care of that for you:
#include <memory>
void foo() // unique pointer
{
std::unique_ptr<MyClass> myObject(new Myclass(myVarA, myVarB, myVarC));
// ...
} // all clean
void goo() // shared pointer -- feel free to pass it around
{
auto myObject = std::make_shared<MyClass>(myVarA, myVarB, myVarC);
// ...
} // all clean
void hoo() // manual -- you better know what you're doing!
{
MyClass * myObject = new MyClass(myVarA, myVarB, myVarC);
// ...
delete myObject; // hope there wasn't an exception!
}
Just to add that setting the pointer to NULL after it's been delete
'd is a good idea so you don't leave any dangling pointers around since attempts to dereference a NULL pointer is likely to crash your application straight away (and so be relatively easy to debug), whereas dereferencing a dangling pointer will most likely crash your application at some random point and be much more difficult to track down and fix.
精彩评论