2

I have an instance of View class (instantiated somewhere in the Controller owning object using shared_ptr)

class ViewController {
protected:
    std::shared_ptr<View> view_;
};

This view has also method "hitTest()" that should return this view's shared_ptr to the outside world

class View {
...
public:
std::shared_ptr<UIView> hitTest(cocos2d::Vec2 point, cocos2d::Event * event) {
...
};

How can I implement this method from inside the View? It should return this VC's shared_ptr to outside? Obviously, I cannot make_shared(this)

hitTest() {
...
    return make_shared<View>(this);
}

because it would break completely the logic: it just would create another smart pointer from the this raw pointer (that would be totally unrelated to owner's shared_ptr) So how the view could know its external's shared_ptr and return it from inside the instance?

barney
  • 2,172
  • 1
  • 16
  • 25

1 Answers1

4

As @Mohamad Elghawi correctly pointed out, your class needs to be derived from std::enable_shared_from_this.

#include <memory>

struct Shared : public std::enable_shared_from_this<Shared>
{
     std::shared_ptr<Shared> getPtr()
     {
         return shared_from_this();
     }
 };

Just to completely answer this questions, as link only answers are frowned upon.

Jan Henke
  • 875
  • 1
  • 15
  • 28
  • how is it possible that Shared type is inherited from the template, templatized by the Shared type itself? i.e compiler should instantiate the enable_shared_from_this template type before the Shared is defined but its publicly inherits its own child? – barney Apr 26 '16 at 11:30
  • 2
    @barney: It's called the CRTP idiom: https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern – dgrine Apr 26 '16 at 11:34
  • @OnMyLittleDuck interestingly I just made a test. the enable_shared... class template - should be unfolding from to a class containing ivar Shared * pointer somewhere inside. so its possible to define: class Shared; class testdrive { Shared * t; }; class Shared : public testdrive { }; as Shared only inherits pointers to its own type from the testdrive - and all compiles ok – barney Apr 26 '16 at 11:37
  • 2
    This answer needs a warning about using `shared_from_this()` on objects which are not managed by some `shared_ptr`. Downvoting until fixed ;-) – jotik Apr 26 '16 at 14:30
  • @Jan Henke what if I am using Poco::SharedPtr instead of std::shared_ptr, what should I use instead of enable_shared_from_this? – X Y Aug 30 '23 at 21:49