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) (No need to show the implementation of class B, consider it as a black box).
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 (consider it as black box as well, just assume it’s happening) where getB() is being called before the initialization of the static variable. What’s happening is the following:
- getB() is being called, and m_b (still nullptr) is being initialized
to a new B(). - intialization of the static variable is being called
again and m_b is being re-assigned to a new B(). - The allocation done in step 1 is not being de-allocated and hence a memory leak.
Can someone please explain the memory leak?