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

前端 未结 2 1847
灰色年华
灰色年华 2020-12-11 03:45

I\'m just toying around with the smart pointers in the upcoming new c++ standard. However I fail to grasp the usage of the shared_from_this function. Here is what I have:

2条回答
  •  时光取名叫无心
    2020-12-11 04:32

    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
    {
    public:
        static std::shared_ptr create() // can only be created as shared_ptr
        {
             return std::shared_ptr(new my_class());
        }
    private
        my_class(){} // don't allow non shared_ptr instances.
    };
    

提交回复
热议问题