views:

34

answers:

1

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

+2  A: 

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.

Reed Copsey