简体   繁体   English

C ++重新分配指针然后删除它

[英]C++ reassign pointer then delete it

Is this safe and correct? 这样安全吗? I mean does the delete care only about the address it is given or is it important to delete the original pointer variable? 我的意思是删除只关心它给出的地址还是删除原始指针变量很重要?

myClass *p1 = new myClass();
myClass *p2 = p1;
delete p2;
p1 = NULL;
p2 = NULL;

删除只关心地址 ,因此您的代码完全合法。

Is this safe and correct? 这样安全吗?

It works . 有效 That is, it has well-defined behaviour and doesn't leak (assuming it compiles). 也就是说,它具有明确定义的行为并且不会泄漏(假设它编译)。

But safe? 但安全吗? It is a dangerous idea to have aliased pointers running around free. 让别名指针随意运行是一个危险的想法。 You have to track which pointers have been deleted and which aren't; 您必须跟踪哪些指针已被删除,哪些指针未被删除; which point to memory that was deleted and which don't. 哪个指向被删除的内存,哪个没有。

It's much safer to use RAII-enabled handles to manage your dynamically allocated objects, like std::unique_ptr and std::shared_ptr (or boost replacements). 使用支持RAII的句柄来管理动态分配的对象会更安全,例如std::unique_ptrstd::shared_ptr (或boost替换)。 std::unique_ptr doesn't allow aliasing, and std::shared_ptr allows aliasing in a safe manner. std::unique_ptr不允许别名, std::shared_ptr以安全的方式允许别名。

Since p1 and p2 point to the same object, then if you delete it through p2, you will also have deleted what pointed p1 to. 由于p1和p2指向同一个对象,如果通过p2 delete它,您也将删除指向p1的内容。 So this is correct. 所以这是正确的。

This is fine. 这可以。 You allocated memory to p1, then referenced the SAME memory in p2. 您已将内存分配给p1,然后在p2中引用了SAME内存。 When you called delete on p2, the memory that p1 was also deleted (they're the same thing, location and all). 当您在p2上调用delete时,p1也被删除的内存(它们是相同的东西,位置和所有内容)。 It's also correct that you set them both to NULL, as deleting p1 otherwise after that may have caused some problems since it was no longer pointing to valid memory. 将它们都设置为NULL也是正确的,因为删除p1之后可能会导致一些问题,因为它不再指向有效的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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