Martin Perry
Martin Perry

Reputation: 9527

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

Upvotes: 1

Views: 87

Answers (1)

kennytm
kennytm

Reputation: 523214

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());
}

Upvotes: 5

Related Questions