how to return shared_ptr to current object from inside the “this” object itself

流过昼夜 提交于 2019-12-10 11:05:29

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/36863240/how-to-return-shared-ptr-to-current-object-from-inside-the-this-object-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!