删除指针
Deleting a pointer
在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
,并且确保不要接受任何主张你做更多的人的建议。
一般建议:避免原始new
和delete
。让一些标准容器处理分配、复制和回收。或者使用智能指针。
干杯,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指针可能会立即使应用程序崩溃(因此相对容易调试),而解引用悬空指针很可能会在某个随机点使应用程序崩溃,并且更难以跟踪和修复。
相关文章:
- 使用函数引用指向节点的指针删除链表中的节点?
- 如何通过指向元组的共享指针删除对象
- 函数内的 C++ 指针删除
- 一个对象的两个指针.删除了一个指针,对象仍然存在
- 如何通过存储在 std::list 中的指针删除对象?
- C++中的智能指针删除
- 将C 中的每个指针删除作为阵列的指针安全吗?
- 使用 C 字符串和指针.删除除小写和空格以外的任何字符
- 在特定情况下,指针删除和铸造之间的关系不清楚
- 提升属性树:使用指向节点及其父节点的指针删除节点
- 警告C4150在尝试包装本机C 类时,指向不完整类型的指针删除
- C++ Valgrind 双指针删除,用于防止内存泄漏
- C 通过指向其基类的指针删除派生对象
- 将指针删除到数组
- 当通过其中一个指针删除对象时,C++将所有指针设置为null
- 智能指针删除器和"using"名称为"pointer"关键字
- 通过指向其基的指针删除 POD 对象是否安全
- 模板化的出列无效指针:删除类时失败
- 使用"this"指针删除
- (C++) list.error 方法和使用指针删除内存