作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
所以,我找到了不同的方法来实现单例的“创建”。
编辑:当我说“创造”时,我是认真的。当然,这段代码将放在 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。我有点知道它的作用,但目的是什么?
此外,请不要将此变成“单例是 BAAAAD”的讨论。
最佳答案
(既然问题好像已经死了,那我就自己来回答吧。)v1
所做的是手动调整 this
指针以指向派生对象的地址。通常,static_cast
或普通的 c 风格转换会自行执行此操作,但在早期的编译器中可能不是这种情况,或者存在错误。不管是什么情况,它都会做类型转换所做的事情。
关于c++ - 单例实现之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4613032/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!