enable_shared_from_this (c++0x): what am I doing wrong?

淺唱寂寞╮ 提交于 2019-11-28 12:07:49

It is a precondition of using shared_from_this that there must exist at least one shared_ptr which owns the object in question. This means that you can only use shared_from_this to retrieve a shared_ptr that owns an object to which you have a reference or pointer, you cannot use it to find out if such an object is owned by a shared_ptr.

You need to rework your design so that either you are guaranteed that any such object is being managed by a shared_ptr or that you don't ever need to know or finally (and least desirably) you create some other way of managing this knowledge.

To extend Charles answer, when you use enable_shared_from_this you usually want something like below in order to guarantee that there exists a shared_ptr.

class my_class : public std::enable_shared_from_this<my_class>
{
public:
    static std::shared_ptr<my_class> create() // can only be created as shared_ptr
    {
         return std::shared_ptr<my_class>(new my_class());
    }
private
    my_class(){} // don't allow non shared_ptr instances.
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!