问题
is there some approach to make singleton class initialize on programs stack (hence members variables also)? I have tried following, both were failed:
1)
class CStack{
public:
void* getAlloc(long);
static CStack& Instance(){
static CStack theStack;
return theStack;
}
private:
bool _data[100];
CStack(){};
CStack(const CStack&);
CStack& operator=(const CStack&);
};
2)
class CStack{
public:
void* getAlloc(long);
static CStack* Instance();
private:
CStack(){};
CStack(CStack const&){};
CStack& operator=(CStack const&){};
static CStack* m_pInstance;
};
CStack* CStack::m_pInstance = NULL;
CStack* CStack::Instance(){
if (!m_pInstance) // Only allow one instance of class to be generated.
m_pInstance = new CStack;
return m_pInstance;
}
first failed due to non-placement new initialization(m_pInstance = new CStack;), second due to lazy initialization. Could, please, someone help me?
Thanks
回答1:
The whole point of singleton is not to rely on when and where it is initialized. The first access would initialize the object, and all subsequent access would yield the same object.
If you put the object on the stack - it will be destructed when the stack is closed (you exit out of the scope), thus future accesses would yield either invalid or a different object, but not the same (as you're out of the scope for the same one).
Thus, by definition of singleton, it cannot be done.
Now, if you explain the problem you're trying to solve, someone may help you with solving it in some more sensible way.
来源:https://stackoverflow.com/questions/8284561/singleton-class-on-callstack