Shared pointers to a singleton do not recognize each other

前端 未结 2 1738
臣服心动
臣服心动 2021-02-10 08:03

I am currently learning how to use the C++11 smart pointers while programming a 2D game engine as a hobby using SDL. However, I ran into a problem while implementing an OOp wrap

2条回答
  •  [愿得一人]
    2021-02-10 08:34

    Rather than keeping a raw pointer in your static member, you should keep a weak_ptr. Use the lock() function to convert back to a shared_ptr; if it comes back empty then you need to allocate a new singleton object.

        static shared_ptr getInstance()
        {
            shared_ptr p = instance_.lock();
            if (!p)
            {
                p = new Foo;
                instance_ = p;
            }
            return p;
        }
    private:
        static weak_ptr instance_;
    

提交回复
热议问题