所以,我找到了不同的方法来实现单例的“创建”。
编辑:当我说“创造”,我的意思是。这段代码当然会放在Singleton :: {ctor}或静态Singleton :: Init()函数中。Singleton实现之间的区别
//v1
//the first "1" is casted to a pointer to Ty, then that pointer is casted
//back to int to obtain the hex address
//the second 1 is casted to a pointer to Ty, then to a pointer
//to cSingleton<Ty> because Ty is a derived class and finally
//back to int to get the hex address
//after that it's simple pointer arithmetics to get the offset
int offset = (int)(Ty*)1 - (int)(cSingleton <Ty>*)(Ty*)1;
m_pSingleton = (Ty*)((int)this + offset);
//v2
m_pSingleton = static_cast<Ty*>(this);
//v3
m_pSingleton = (Ty*)this;
它们之间有任何显着差异吗?
据我所知,v2和v3应该是相同的,但它的v1我不是很了解。我知道它做了什么,但是为了什么目的?
另外,请不要把它变成“Singletons are BAAAAD”的讨论。
WTH是吗?看起来像参加这个比赛:www.ioccc.org/main.html – 2011-01-06 08:31:37
um。你可以通过静态指针指向类来创建一个单例,然后创建一个静态工厂函数来创建这个类,或者返回现有的指针。我不知道这段代码在做什么,除了很多不必要和危险的演员。 – 2011-01-06 08:32:16
@Xeo nice gravatar – abel 2011-01-06 08:36:34