如何检测“悬空指针"如果“已分配()"做不到吗? [英] How to detect "dangling pointers" if "Assigned()" can't do it?

查看:16
本文介绍了如何检测“悬空指针"如果“已分配()"做不到吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在另一个问题中,我发现 Assigned() 函数与 Pointer <>无.我一直认为 Assigned() 正在检测这些悬空指针,但现在我知道它没有.悬空指针是那些可能在某一时刻创建的指针,但后来被释放并且尚未分配给 nil.

In another question, I found out that the Assigned() function is identical to Pointer <> nil. It has always been my understanding that Assigned() was detecting these dangling pointers, but now I've learned it does not. Dangling Pointers are those which may have been created at one point, but have since been free'd and haven't been assigned to nil yet.

如果 Assigned() 不能检测悬空指针,那么什么可以?在我尝试使用它之前,我想检查我的对象以确保它确实是一个有效的创建对象.我不像很多人推荐的那样使用 FreeAndNil,因为我喜欢直接.我只是使用 SomeObject.Free.

If Assigned() can't detect dangling pointers, then what can? I'd like to check my object to make sure it's really a valid created object before I try to work with it. I don't use FreeAndNil as many recommend, because I like to be direct. I just use SomeObject.Free.

访问违规是我最大的敌人 - 我尽我所能防止它们出现.

Access Violations are my worst enemy - I do all I can to prevent their appearance.

推荐答案

如果您在作用域中有一个对象变量,并且它可能是也可能不是有效的引用,那么您应该使用 FreeAndNil.或者修复您的代码,以便您的对象引用得到更严格的管理,因此这从来都不是问题.

If you have an object variable in scope and it may or may not be a valid reference, FreeAndNil is what you should be using. That or fixing your code so that your object references are more tightly managed so it's never a question.

不应将访问冲突视为敌人.它们是错误:它们意味着您犯了一个需要修复的错误.(或者您所依赖的某些代码中存在错误,但我发现最常见的是我自己搞砸了,尤其是在处理 RTL、VCL 或 Win32 API 时.)

Access Violations shouldn't be thought of as an enemy. They're bugs: they mean you made a mistake that needs fixed. (Or that there's a bug in some code you're relying on, but I find most often that I'm the one who screwed up, especially when dealing with the RTL, VCL, or Win32 API.)

这篇关于如何检测“悬空指针"如果“已分配()"做不到吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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