所以,我找到了不同的方法來實現單例的「創建」。
編輯:當我說「創造」,我的意思是。這段代碼當然會放在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