Pointers to automatically null when object is dele

2020-07-19 03:06发布

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.

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.

标签: c++ pointers
2条回答
手持菜刀,她持情操
2楼-- · 2020-07-19 04:03

"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.

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.

查看更多
forever°为你锁心
3楼-- · 2020-07-19 04:08

Auto pointers and shared pointers etc are basically just classes that handle this kind of stuff for you. But it sounds like you've got a slightly different requirement, so I think you should develop your own class to manager pointers and use that instead of the raw pointers. That way you should be able to get the slick functionality that you're looking for.

查看更多
登录 后发表回答