c++ - Singleton 实现之间的差异

标签 c++ singleton

所以,我找到了不同的方法来实现单例的“创建”。
编辑:当我说“创造”时,我是认真的。当然,此代码将放置在 Singleton::{ctor} 或静态 Singleton::Init() 函数中。

//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我不太明白。我有点知道它的作用,但目的是什么?

另外,请不要把这变成“单例太糟糕了”的讨论。

最佳答案

(既然这个问题似乎已经死了,我会尝试自己回答。)
v1 所做的是手动调整 this 指针以指向派生对象的地址。通常,static_cast 或普通的 c 风格强制转换会自行执行此操作,但早期编译器可能并非如此,或者存在错误。无论情况如何,它都会执行强制转换的操作。

关于c++ - Singleton 实现之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4613032/

相关文章:

python - 将闭包从 Cython 传递到 C++

C++单例设计问题

objective-c - cocoa 中的单例,他们是邪恶的吗?

javascript - 单例模块和导入全局 jQuery 对象

javascript - 依赖node.js模块状态可以吗?

c++ - 运行时错误 : signed integer overflow: 964632435 * 10 cannot be represented in type 'int'

android - JNI 错误(应用程序错误): attempt to use stale Local 0x31 (should be 0x39)

单例上的 C++

c++ - 通过函数参数获取数组

c++ - 广义混合