如何检测指针是否被删除并安全地删除它? [英] How to detect if a pointer was deleted and securely delete it?

查看:960
本文介绍了如何检测指针是否被删除并安全地删除它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 中如何决定或知道指针是否在删除前



在代码的另一部分删除它抛出一个无法处理的异常。



我想知道是否有一种方法来检查或尝试删除指针?任何关于高级内存操作的引用。



我也想掌握未处理的指针异常,并且访问受保护或访问是违反,...这种



感谢那些给了他们一些知识和时间帮助其他人并分享他们的信仰的人



< hr>

更新



许多现代c ++开发人员社区的大意见是 - 使用智能指针或尝试避免使用原始指针。但是为了保证安全并确保免费内存( ISO_CPP_FAQ ),当然如果你想避免使用智能指针的小开销[可能不会注意到总是但他们有开销]你可以编写你的自定义方法处理原始指针[类型*] - 这不是一般的。
总是指向原始指针



在Going Native 2013​​中,常见的建议是 - 不要使用原始指针。

解决方案

可以有三种解决方案。



优雅且最正确的解决方案:



使用 智能指针 ,您不必再次手动调用 delete 。这是克服这个问题的最好的方法。它使用RAII的原理,它完美地适用于C ++这样的语言,它没有内置的垃圾收集器。


$ b

不太优雅但可行的解决方案:



将指针指向 NULL 。在 NULL 指针上调用 delete 是一个无操作,因此它不再需要额外的 NULL 检查,但这可能会隐藏一些问题,而不是让它们可见。



不太优雅但更正确的解决方案:



code> delete 问题,让你的程序崩溃。你可以使用内存分析器程序,如valgrind,然后修复你的代码,以避免所有这些问题。


In C++ How to decide or know if a pointer was deleted before??

when i tried to delete a pointer that was previously deleted in another part of the code it threw an exception that can't be handled.

I was wondering if there is a way to check or try delete the pointer ? any reference about advanced memory operations.

also i want to master the un-handled exceptions of pointers and the access to protected or access is violation ,... this kind of error.

thanks for those who give some of their knowledge and their time to help other people and share their benfits


Update

The big advice from a lot of modern c++ developers community is - Use smart pointers or try to avoid the use of raw pointers. But for throw security and insuring free of memory (ISO_CPP_FAQ) and of course if you want to avoid the small overhead of using smart pointers[may not be noticeable always but they have overhead] you can write your custom methods that deal with raw pointers [type*] - this is not general. Prefer always smart pointers to raw pointers.

In 'Going Native 2013' a common advice given was - Never use raw pointers.

解决方案

There can be three solutions. You might want to choose one depending on the effort/quality ratio you want to acheive:

Elegant and most correct solution:

Use smart pointers and you do not have to manually call delete ever again. This is the best possible way to overcome this problem. It utilizes the principle of RAII which works perfectly for a language like C++ which does not have an in-built garbage collector.

Less elegant but workable solution:

Assign the pointer to NULL after deletion. Calling delete on a NULL pointer is a no-op so it removes the need to have that extra NULL check but this might hide some problems instead of making them visible.

Less elegant but more correct solution:

Hunt down all the multiple delete problems by letting your program crash. You might as well use memory analyzer programs like valgrind and then fix your code to avoid all these problems.

这篇关于如何检测指针是否被删除并安全地删除它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆