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:
Can someone please explain the memory leak? And what is the best way to solve it?
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;
}