Search code examples
c++shared-ptrdouble-dispatchweak-ptr

std::shared_ptr and double callback


I have some logic where I am using std::shared_ptrs to objects in an inheritance hierarchy. At one point I need to handle these objects depending on their real type, so I am using a double dispatch (i.e. I call a method on the base class, which then in turn calls a method on another object with the real type, see e.g. visitor pattern in GoF).

Now at this point I could either pass a reference to the object with the correct type or a copy. For several reasons a copy is out of question. A reference would normally be fine, because the call happens in a scope below the one where the shared_ptr lives, so it won't be destroyed while this call happens. However for some sub types I need to store the object in an STL Container, so I need to be absolutely sure it won't be destroyed. Obviously bare pointers or new shared_ptrs wont work here, so I need to get the reference to the shared_ptr from which this was called.

Right now I am doing the following: I use a named constructor instead of a real one to create the object. This sets a weak_ptr inside the object and gives out a shared_ptr for usage of the object. When the double callback happens, I get a new shared_ptr from the weak_ptr and store this one in the Container, so the object wont get destroyed. However this makes my logic for construction really ugly.

Is there any better way to do this?


Solution

  • Derive your class from std::enable_shared_from_this - then you can extract a shared_ptr from your object at any time!

    It's not a whole lot different from what you're doing now with the weak_ptr, but it's the clean and accepted idiom to do it.