c++memorymemory-leaksstaticunique-ptr

Memory leak using a static unique_ptr member


I'll try to summarize the usecase as much as possible.

I have a class A (Defined in A.hpp):

class A
{
public:
   static B& getB();
private:
   A();
   static std::unique_ptr<B> m_b;
};

that uses a class B (Also defined in A.hpp)

class B
{};

In A.cpp, we define our static member A::m_b as :

std::unique_ptr<B> A::m_b = std::unique_ptr<B>(new B());

We also implemented the getB() (Also in A.cpp) method as :

B& A::getB()
{
   if (!m_b)
   {
      m_b= std::unique_ptr<B>(new B());
   }
   return *m_b;
}

I have a scenario where another static variable (call it X) is calling getB() before the initialization of the m_b variable. What is happening is the following:

  1. getB() is being called, and m_b (still nullptr) is being initialized to a new B().
  2. intialization of the static variable is being called again and m_b is being re-assigned to a new B().
  3. The allocation done in step 1 is not being de-allocated and hence a memory leak.

Can someone please explain the memory leak? And what is the best way to solve it?


Solution

  • As the comments note, this indicates that A::getB is called before A::m_b is initialized. Hence, A::getB is accessing an uninitialized variable. And no, you can't fix that by then "initializing" m_b like you currently try.

    Since accessing uninitialized variables is Undefined Behavior, anything can happen including memory leaks. The fix is the Meyers Singleton suggested by Christian Stieber:

    B& A::getB()
    {
        static B b;
        return b;
    }