So, i found different ways to implement the “creation” of the singleton.
EDIT: When I say “creation”, I mean it. This code would be placed in the Singleton::{ctor} or static Singleton::Init() functions of course.
//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;
Is there any significant difference between them?
To my knowledge, v2 and v3 should be the same, but it’s v1 I don’t really understand. I kinda know what it does, but for what purpose?
Also, please don’t turn this into a “Singletons are BAAAAD” discussion.
(Since the question seems to have died, I’ll try to answer it on my own.)
What
v1does is manually adjusting thethispointer to point to the address of the derived object. Normally,static_castor a normal c-style cast does this by itself, but maybe that wasn’t the case on earlier compilers or there was a bug. What ever is the case, it does what the casts do.