删除指针

Deleting a pointer

本文关键字:指针 删除      更新时间:2023-10-16

在c++中,推荐的删除指针的方法是什么?例如,在下面的例子中,我是否需要所有三行来安全地删除指针(如果需要,它们是怎么做的)?

// Create
MyClass* myObject;
myObject = new MyClass(myVarA, myVarB, myVarC);
// Use
// ...
// Delete
if(myObject) { 
    delete myObject; 
    myObject = NULL; 
}

不,您不需要检查NULL
delete会注意传递的指针是否为NULL

delete myObject; 
myObject = NULL; 

是充分的。

作为一般策略,尽可能避免使用自由分配,如果必须使用智能指针(RAII)而不是原始指针。


c++ 03标准断面§3.7.3.2.3:

提供给标准库中提供的释放函数的第一个参数的值可以是空指针值;如果是,则调用释放函数对不起作用。否则,标准库中提供给operator delete(void*)的值必须是先前调用operator new(size_t)或operator new(size_t, const std::nothrow_t&)所返回的值之一,而标准库中提供给operator delete的值必须是先前调用operator new或operator new[](size_t, const std::nothrow_t&)所返回的值之一。

不,你不需要。

只写delete p,并且确保不要接受任何主张你做更多的人的建议。

一般建议:避免原始newdelete。让一些标准容器处理分配、复制和回收。或者使用智能指针。

干杯,hth。

最好使用资源管理类,并让库为您处理:

#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 'd之后将指针设置为NULL是一个好主意,这样您就不会留下任何悬空指针,因为尝试解引用NULL指针可能会立即使应用程序崩溃(因此相对容易调试),而解引用悬空指针很可能会在某个随机点使应用程序崩溃,并且更难以跟踪和修复。