Bring you two different implantation of singleton design pattern:
static class member
class SingletonCSM;
using SingletonCSMSp = std::shared_ptr < SingletonCSM > ;
class SingletonCSM
{
public:
~SingletonCSM() { spInstance = nullptr; }
static SingletonCSMSp GetInstance()
{
if (!spInstance)
spInstance = std::make_shared<SingletonCSM>();
return spInstance;
}
private:
SingletonCSM() {}
// will be intilized in the cpp: SingletonCSMSp SingletonCSM::spInstance = nullptr;
static SingletonCSMSp spInstance;
};
static member variable
class SingletonFSV;
using SingletonFSVSp = std::shared_ptr < SingletonFSV > ;
class SingletonFSV
{
public:
~SingletonFSV() {}
static SingletonFSVSp GetInstance()
{
static SingletonFSVSp spInstance = std::make_shared<SingletonFSV>();
return spInstance;
}
private:
SingletonFSV() {}
};
I always use the first impl. SingletonCSM
. I came across, in our code, an impl. like SingletonFSV
Questions
- Can we consider both impl. as a valid impl. of the design pattern?
- Are both, functionally, the same?
Motivation
Background
Class SingletonFSV
was implemented as a part of a DLL project. This DLL, compiled in VS 2013
, is loaded in memory by an exe file and run.
Problem
I've upgrade my VS
to VS 2015
, compiled the DLL project and run the exe. All of a sudden, it crashed. While debugging, I've notice that the crash happened in the DLL itself. make_shared
called withing GetInstance()
returned nullptr
and naturally caused segmentation fault.
Solution
I've changed SingletonFSV
impl. to SingletonCSM
and the crash stopped. make_shared
returned a valid pointer and the problem was solved.
Question
I just don't understand what was the problem and why was it solved?