Search code examples
c++c++11shared-ptr

C++ shared_ptr return this from derived method


I have been using this:

struct Bar;

struct Foo 
{
   virtual Bar * GetBar() { return nullptr; }
}

struct Bar : public Foo
{
   virtual Bar * GetBar() { return this; }
}

Foo * b = new Bar();
//...
b->GetBar();

I used this instead of slow dynamic_cast. Now I have changed my code to use std::shared_ptr

std::shared_ptr<Foo> b = std::shared_ptr<Bar>(new Bar());

How can I change GetBar method to return std::shared_ptr and get the same functionality as with raw pointers (no need for dynamic_cast) ?

I have tried this:

 struct Foo : public std::enable_shared_from_this<Foo>
 {
     virtual std::shared_ptr<Bar> GetBar() { return nullptr; }
 } 


struct Bar : public Foo
{
    virtual std::shared_ptr<Bar> GetBar() { return shared_from_this(); }
}

But it wont compile


Solution

  • std::enable_shared_from_this<Foo>::shared_from_this() returns a shared_ptr<Foo>. So you need an explicit pointer downcast.

    virtual std::shared_ptr<Bar> GetBar() {
        return std::static_pointer_cast<Bar>(shared_from_this());
    }