调用堆栈上的Singleton类 [英] Singleton class on callstack

查看:61
本文介绍了调用堆栈上的Singleton类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一些方法可以使单例类在程序堆栈上初始化(因此也有成员变量)?我尝试过的
都失败了:

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;
}

第一次由于未放置新的初始化而失败(m_pInstance = new CStack;) ,第二个由于延迟初始化。

first failed due to non-placement new initialization(m_pInstance = new CStack;), second due to lazy initialization. Could, please, someone help me?

谢谢

推荐答案

单例的全部意义不在于何时何地被初始化。第一次访问将初始化该对象,而所有后续访问将产生相同的对象。

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.

这篇关于调用堆栈上的Singleton类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆