[问题] Singleton 与效率的问题

楼主: leondemon (狗狗)   2014-11-20 00:20:36
大家好 我几乎没在写 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 因为会用不到)
这样应该要怎么实作会比较好呢?
作者: Ebergies (火神)   2014-11-20 00:33:00
建议你假装没有这种东西存在,它在以后会阻碍你
楼主: leondemon (狗狗)   2014-11-20 01:14:00
是指Singleton吗?
作者: yoco (眠月)   2014-11-20 01:35:00
恩,假装没有这东西对你会有很多好处
楼主: leondemon (狗狗)   2014-11-20 01:57:00
那有什么办法可以在不同地方取得同一个物件呢?例如一个 global function=> getSharedInstance();然后可以在不需要时手动移除 releaseSharedInstance()我以为 Singleton pattern 在 C 应该是蛮常见的... 囧
作者: Caesar08 (Caesar)   2014-11-20 07:27:00
如果用A *a,就可以解决你的第一个问题
作者: yoco (眠月)   2014-11-20 08:28:00
error1: 对,要把定义移到前面。error2: 请问错误讯息是什么?
作者: Killercat (杀人猫™)   2014-11-20 08:59:00
他的error2是由error1引发的 修掉1应该就可以了另外Singleton在C并不常见,C几乎都用Global Extern另外实作上Singleton我会建议直接用Loki就好Loki Singleton_Holder能解决绝大多数的问题
作者: descent (“雄辩是银,沉默是金”)   2014-11-20 09:30:00
干脆用 global variable 就好
作者: littleshan (我要加入剑道社!)   2014-11-20 10:38:00
在不同地方取得同一物件 → 用参数传递传参数比较麻烦没错,但global state造成的麻烦更大但这件事真的要很有经验才能理解它造成什么麻烦
作者: dirkc (3781615)   2014-11-20 12:16:00
C++很常用的cout/cin即是用extern
作者: littleshan (我要加入剑道社!)   2014-11-21 12:09:00
我会思考不用 attribute 的方法不过你们的情况可能混合别人的code或是已经改不动那就真的没办法了

Links booklink

Contact Us: admin [ a t ] ucptt.com