views:

660

answers:

3
+4  A: 

Take a look at the source for Boost shared pointers. If you derive a class from enable_shared_from_this<T>, you can then call the shared_from_this() member function to do that sort of thing.

Ferruccio
+1. I've used boost::shared_ptr and shared_from_this before and it works very well
Orion Edwards
A: 

As far as semantics go, the great thing about immutability is that you can safely share data between objects, threads, and not have to worry about people changing values you depend on. You shouldn't need to worry about ownership so long as your refcounting scheme is correct (I didn't read yours, but use Boost anyway).

wowest
A: 

As eluded to by Ferruccio, you need some form of shared pointer. Ie, one that can be shared (safely!) between multiple objects. One way to make this work is to derive all your objects (at least those that are intended for use with the shared pointer) from a class that implements the actual reference count. That way, the actual pointer itself carries the current count with it, and you share the pointer between as many different objects as you like.

What you currently have is very similar to std::auto_ptr and you are bumping into the same issues with ownership. Google it and you should find some useful info.

Be aware that there are additional complications with shared pointers: in particular in multi-threaded environments your reference counting must be atomic and self assignment must be handled to avoid incrementing the internal count such that the object is never destroyed.

Again google is your friend here. Just look for info on shared pointers in C++ and you'll find tonnes of info.

Gian Paolo