views:

74

answers:

3

Hi all,

I have a question regarding shared_ptrs and ownership in C++:

I have a bunch of objects created on the heap. Each one has a container which holds pointers to some of these objects, and sometimes, even a pointer to the same object the container belongs to. Since I read about the risks of using shared_ptr under such circumstances (circularity), I'm thinking about how to do it best. Luckily, there is a class that holds all of the objects in question (but not itself), so I thought I give it ownership over them, so that its container holds shared_ptrs while the objects in question hold raw pointers. That is, destruction of the class frees the heap-allocated memory. Is this (also in terms of design) a good decision to make?

Another thougth was not to let the objects hold pointers, but rather unique IDs. This would imply a lookup to actually get an object via its ID, however, I think it would also reduce critical dependecies among the objects. Is this preferable?

Regards,

Jena

+1  A: 

Perhaps using weak_ptr can help you:

http://stackoverflow.com/questions/3577268/boostshared-ptr-cycle-break-with-weak-ptr

Peter G.
+4  A: 

You probably want to look up Boost weak_ptr.

Jerry Coffin
Thanks for the reference, that looks promising!
jena
+1  A: 

This is a subjective answer, so .. .

Most of the time when you really know the lifetime of your objects and you control their dependencies, you can use your stated approach. There is nothing wrong, using only pointers, when lifetime is a non-issue.

Using ids just adds a new 'id' for the pointer value and so adds an 'useless' indirection when using the objects.

The downside is, that you cannot (or should not) hand out references to the objects to other code, that may extend the lifetime of your objects.

When some part of your collections could extend the lifetime of its referenced objects to something longer then the 'lifetime-owner-container', use boost::weak_ptr.

Christopher
I think I agree that a unique ID would be somewhat redundant. I will take a look at boost::weak_ptr and see if it's appropriate for my problem.
jena