如何从“this”内部将shared_ptr返回到当前对象。对象本身 [英] how to return shared_ptr to current object from inside the "this" object itself

查看:464
本文介绍了如何从“this”内部将shared_ptr返回到当前对象。对象本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个View类的实例(在Controller拥有对象中使用shared_ptr实例化)

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_;
};

此视图还有方法hitTest(),应该将此视图的shared_ptr返回到外部世界

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) {
...
};

如何在View中实现这个方法?它应该将这个VC的shared_ptr返回到外部?
显然,我不能 make_shared(this)

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

因为它会完全破坏逻辑:它只会创建另一个智能指针这个原始指针(这将完全与所有者的shared_ptr无关)
那么视图如何知道其外部的shared_ptr并从实例中返回呢?

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?

推荐答案

正如@Mohamad Elghawi正确地指出,你的类需要从 std :: enable_shared_from_this 派生。

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.

这篇关于如何从“this”内部将shared_ptr返回到当前对象。对象本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆