gpt4 book ai didi

c++ - 单例实现之间的区别

转载 作者:搜寻专家 更新时间:2023-10-31 01:58:06 24 4
gpt4 key购买 nike

所以,我找到了不同的方法来实现单例的“创建”。
编辑:当我说“创造”时,我是认真的。当然,这段代码将放在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com