0

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 give some direction?
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:
        ...
}
IgNite
  • 652
  • 2
  • 6
  • 17

1 Answers1

2

One of the reasons it's returned by reference is to reset the static shared pointer. You can see that there is some logic to create a new one for whatever business logic the static pointer could need to be reset.

And no, no logic for threads here.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • Hmm great point! I also question myself why would one want to check that line: `if (inst == nullptr)`. – IgNite Jan 19 '19 at 19:22
  • I'd like to spend some time a bit more diving into the code to see exactly why. But your answer gives me a really good direction of where to look into. – IgNite Jan 19 '19 at 19:29