删除对象时指针自动为空 [英] Pointers to automatically null when object is deleted

查看:104
本文介绍了删除对象时指针自动为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个对象和在不同类类型的其他几个对象中有10个指针.如果对象被删除,则必须将这些指针设置为null.通常,我会将对象的类与具有指向它的指针的类互连,以便它可以通知它们正在被删除,并且可以将其指针设置为null.但这也带来了负担,当删除它们时,类还必须通知对象,因为对象也将需要指向它们的指针.这样,对象在破坏并尝试通知其他对象时就不会调用取消引用悬挂指针.

Say I have an object and 10 pointers to it in several other objects of varying class types. if the object gets deleted, those pointers have to be set to null. normally I would interconnect the object's class with the classes which have pointers to it so that it can notify them it is being deleted, and they can set their pointers to null. but this also has the burden that the classes must also notify the object when THEY are deleted since the object will need a pointer to them as well. That way the object doesn't call dereference a dangling pointer when it destructs and attempts to notify the others.

我不喜欢这种令人困惑的废话,我正在寻找一种更好的方法.

I don't like this confusing web of crap and I'm looking for a better method.

请注意,自动指针和共享指针不是我想要的-自动指针在销毁对象时会删除其对象,而共享指针在没有其他共享指针指向时会执行相同的操作.我正在寻找的是一种巧妙的方法,用于在对象破坏时将指向该对象的所有指针设置为null.

Please note that auto pointers and shared pointers are not what I'm looking for - auto pointers delete their object when they destruct, and shared pointers do the same when no more shared pointers are pointing to it. What I'm looking for is a slick method for setting all pointers to an object to null when the object destructs.

推荐答案

计算机科学中的所有问题都可以通过另一种间接解决方案来解决"-David Wheeler

"All problems in computer science can be solved by another level of indirection" -- David Wheeler

对于您来说,效果很好的是

In your case, what will work very well is

std::shared_ptr<Object*> pp.

删除对象时,将共享的Object*设置为null(例如*pp = 0;).所有其他用户正在共享Object*,现在将看到它已变为空.当所有用户都离开时,用于Object*本身的内存也将被释放.

When you delete the object, set the shared Object* to null (e.g. *pp = 0;). All the other users are sharing the Object*, and will now see that it has become null. When all the users are gone, the memory used for the Object* itself will also be freed.

这篇关于删除对象时指针自动为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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