Sign in to follow this  
johnstanp

Creating a shared_ptr to this

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites
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...

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this