开发者

Difference between Singleton implementations

开发者 https://www.devze.com 2023-02-02 13:06 出处:网络
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() func

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 开发者_JAVA百科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 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.


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:

  • cast the number 1 to a pointer of my type Ty, and back to an int. I would expect this to still yield 1.
  • cast the number 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.
  • subtract the two. I would expect this to be 0.
  • set the singleton to 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.


Here is a nice singleton C++ example. I have no idea why you're using this kind of coding, this is hardly good practice.

0

精彩评论

暂无评论...
验证码 换一张
取 消