大家好 我几乎没在写 C++ 算是个很新的新手
查了 C++ 的 Singleton 的作法 遇到了一些问题,想请教各位高手
这边是 SO 的讨论
http://stackoverflow.com/questions/1008019/c-singleton-design-pattern
于是我依样话葫芦 实作了以下 (绿色为新增的部分 黄色为引发问题的注解)
class A;
typedef std::map<std::string, A> DictA;
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.
// Dont forget to declare these two. You want to make sure they
// are unaccessable otherwise you may accidently get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
A a; // Compile Error 1
DictA _dict; // Compile Error 2
};
class A {
public:
A();
};
稍微研究一下 上面的 code 引发了两个 compile error
Compile Error 1:
这部份需要把 class A 宣告搬到 class S 前面
似乎 forward declaration 不适用
想问一下一定需要把 class A 宣告在前面吗?
Compile Error 2:
这不部分就不晓得为什么引起 error
(implicit instantiation of undefined template)
似乎跟 Singleton 的实作有关 (static instance?)
最后想要问一个问题 我想做一个 singleton
并且有一个 dictionary(map) 可以高效率读写资料
最后这个 singleton 可在特定时间清除所有资料 (甚至 delete 因为会用不到)
这样应该要怎么实作会比较好呢?