samedi 19 janvier 2019

Return `std::shared_ptr` as reference

I am reading some codebase but I don't quite understand why the below function would return a reference (&) to the std::shared_ptr. I read in this stackoverflow question that we should return std::shared_ptr by value, because otherwise we won't properly increment the reference count.

So I am just trying to guess the reason.

  • Does it have something to do with the the member function being static? Or the return value being static?
  • Does it have something to do with thread as the name suggests? Could anyone point me to some reading or explain why?
class A {
    public:
        A() {...}
        ~A() {...}
        ...
        static std::shared_ptr<A>& ThreadLocal() {
            static std::shared_ptr<A> inst = std::make_shared<A>();
            if (inst == nullptr) {
                inst = std::make_shared<A>();
            }
            return inst;
        }
        static void Shutdown() {
            ThreadLocal().reset();
        }
    private:
        ...
}

Aucun commentaire:

Enregistrer un commentaire