【发布时间】:2013-10-14 19:10:56
【问题描述】:
最近有人问我关于 c++ 中的单例设计模式。我不确切知道它的作用或需要它的时间,所以我尝试用谷歌搜索它。我主要在 stackoverlow 上找到了很多答案,但我很难理解这些问题和答案中提到的代码。我知道单身人士应该满足以下属性,如果我错了,请纠正我。
It is used when we need to make one and only one instance of a class.
这在我的脑海中提出了以下问题
Does this mean that it can be created only once or does this mean that it can be
created many times but at a time only one copy can exist?
现在开始实施。 复制自here
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {}; // Constructor? (the {} brackets) are needed here.
// Don't forget to declare these two. You want to make sure they
// are inaccessible otherwise you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
};
请解释一下:
- 为什么我们必须将 getinstace() 函数设为静态?
- 为什么我们需要 S(S const&);构造函数?
- 什么是 void operator=(S const&);做什么?
- 为什么我们不实现最后两个函数?
- 为什么我们需要保证销毁此实例(如代码中所述)?
【问题讨论】:
标签: c++ class design-patterns static singleton