Reputation: 131837
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.
Upvotes: 2
Views: 389
Reputation: 131837
(Since the question seems to have died, I'll try to answer it on my own.)
What v1
does is manually adjusting the this
pointer to point to the address of the derived object. Normally, static_cast
or 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.
Upvotes: 2
Reputation: 15069
Here is a nice singleton C++ example. I have no idea why you're using this kind of coding, this is hardly good practice.
Upvotes: 0
Reputation: 9172
v2 and v3 are pretty much the same, but v3 is using a c-style cast (c++ style casting is safer, as you get more checks at compile time).
v1 is... wow... Here's what it's doing:
1
to a pointer of my type Ty
, and back to an int
. I would expect this to still yield 1
.1
to a pointer of my type Ty
, cast that to a pointer of cSingleton<Ty>
, and finally back to an int
. I would expect this to also still be 1
.this
, like in v2 and v3, but adjust for the "offset"I'm guessing there's some quirk of architecture someplace where the result of casting 1 leads you to a non-1 result, so the offset would be non-zero. So this would be a way to adjust for casting quirks on a platform.
That's a guess though, and I would hope there would be some comments to explain the code (but probably not). Maybe someone can chime in with a more concrete answer than mine, but hopefully this gives you something to go on.
Upvotes: 1