Creating a shared_ptr to this

Started by
4 comments, last by rip-off 14 years, 3 months ago
Well, the question is in the title. I am trying to implement an Octree class. All children of an octree must have a smart pointer( here a boost::shared_ptr ) to their parent. How can I do this?
Advertisement
Have a look at the docs for "enable_shared_from_this". Inherit this into a class, and it now has a "shared_from_this" which will do what you need.

Note that it's actually a weak_ptr not a shared_ptr.

You probably want the parent pointer to be a "weak_ptr", because the parent "owns" the nodes, but the nodes just reference the parent. In this case, creating a child is done by the parent, which can copy its "shared_from_this" into the appropriate member of the new child so the child points back to it.

I would use enable_shared_from_this if I was handing shared pointers outside the class. In the case of an Octree with weak parent pointers, I would probably use raw pointers because they never leak outside the class itself. Implementing a data structure is one of the few places where I consider not using smart pointers. IF you do choose this route you must be careful when implementing the copy constructor and assignment operator (or explicitly disable them).
Quote:Original post by Katie
Have a look at the docs for "enable_shared_from_this". Inherit this into a class, and it now has a "shared_from_this" which will do what you need.

Note that it's actually a weak_ptr not a shared_ptr.

You probably want the parent pointer to be a "weak_ptr", because the parent "owns" the nodes, but the nodes just reference the parent. In this case, creating a child is done by the parent, which can copy its "shared_from_this" into the appropriate member of the new child so the child points back to it.


Thanks, that's done...

Quote:Original post by rip-off
I would use enable_shared_from_this if I was handing shared pointers outside the class. In the case of an Octree with weak parent pointers, I would probably use raw pointers because they never leak outside the class itself. Implementing a data structure is one of the few places where I consider not using smart pointers.


Is it partly because the children nodes are always deleted before the parent one?
Yes. Using shared pointers here will require more allocations and will be (marginally) slower. There is another issue, which is that unless you have taken steps to prevent this, your octree will have a shallow copy constructor, which is highly surprising to client code.

This topic is closed to new replies.

Advertisement