Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enable_shared_from_this and inheritance

I've got a type which inherits from enable_shared_from_this<type>, and another type that inherits from this type. Now I can't use the shared_from_this method because it returns the base type and in a specific derived class method I need the derived type. Is it valid to just construct a shared_ptr from this directly?

Edit: In a related question, how can I move from an rvalue of type shared_ptr<base> to a type of shared_ptr<derived>? I used dynamic_cast to verify that it really was the correct type, but now I can't seem to accomplish the actual move.

like image 911
Puppy Avatar asked Dec 20 '10 16:12

Puppy


1 Answers

Once you obtain the shared_ptr<Base>, you can use static_pointer_cast to convert it to a shared_ptr<Derived>.

You can't just create a shared_ptr directly from this; that would be equivalent to:

shared_ptr<T> x(new T());
shared_ptr<T> y(x.get()); // now you have two separate reference counts
like image 168
James McNellis Avatar answered Nov 09 '22 23:11

James McNellis