开发者

C++ Managing Shared Object's Handle issues

Is there best practice for managing Object shared by 2 or more others Object. Even when running on different thread?

For example A is created and a pointer to it is given to B and C. ObjA A = new ObjA(); B->GiveObj(A); C->GiveObj(A);

Now how can I delete objA?

So far what I though about is A monitor 开发者_运维问答how many ref there are to it and when this counter is 0 it delete this (such as when A is passed, the receiver call A->Aquire(), when its done it call A->release();

Or I could tell B->RemoveObj(A); and C->RemoveObj(A); The problem with that is if B or C are running on a different thread, I cannot delete A until they are done with A, and they have seen The RemoveObj call. (Which require a bunch of messy flags).

Would there be a nice way to do this, possibly with Signal/Slot?

Thanks


The best option is to use a smart pointer implementation such as Boost's shared_ptr.

This allows you to pass around the pointers as needed, without worrying about the deletion.


Edit:

I just realized you had the signal/slot tag added. If by chance you're using Qt, you probably want QSharedPointer (or similar) instead of a boost pointer implementation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜