简体   繁体   中英

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 myObject; 
    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!
}

只是添加将其delete后将指针设置为NULL是一个好主意,因此您不会留下任何悬空的指针,因为尝试取消引用NULL指针可能会立即使您的应用程序崩溃(因此相对容易进行调试),而取消引用悬空指针将很可能在某个随机点使您的应用程序崩溃,并且更难追踪和修复。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM