29

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
Puppy
  • 144,682
  • 38
  • 256
  • 465

1 Answers1

22

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
James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • 1
    No, you can't downcast `shared_ptr` to `shared_ptr` with `static_pointer_cast`. One has to use `dynamic_pointer_cast` as there may be any number of derived classes. – Myon Nov 07 '17 at 13:33
  • 1
    @Myon Why not? What do you mean? – curiousguy Jun 10 '18 at 18:05
  • 2
    @curiousguy: You can use `static_pointer_cast` if you're using non-virtual inheritance and you're 100% sure of the type you are casting to. Any other case is undefined behavior. So in general use `dynamic_pointer_cast` and you'll be on the safe side - that's what I ment. – Myon Jun 11 '18 at 09:09