[英]How does the following code work?
#define TYPE_CHECK(T, S) \
while (false) { \
*(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
}
I am reading Google v8 's code and found the above macro for type check. 我正在阅读谷歌v8的代码,发现上面的宏进行类型检查。
However, I do not understand why it works. 但是,我不明白为什么会这样。 while(false) never get executed, right?
虽然(假)永远不会被执行,对吧? Can someone explain those lines?
有人可以解释这些线吗? Thanks
谢谢
Quite a fancy hack - the purpose of the macro seems to be to check if the type S
is assignable to (ie, is a subclass of) the type T
. 相当奇特的黑客 - 宏的目的似乎是检查类型
S
是否可分配给类型T
(即,是子类)。 If it is not, the pointer cast from S*
to T*
will produce a compiler error. 如果不是,则从
S*
为T*
的指针将产生编译器错误。 The while (false)
prevents the code from actually having any other effect. while (false)
阻止代码实际产生任何其他影响。
Yes, but the compiler still performs syntax & semantic checks on the loop contents. 是的,但编译器仍然对循环内容执行语法和语义检查。 So if something is wrong (ie the implicit type conversion from
S*
to T*
is illegal, which happens if T
is neither S
nor a base class of S
), compilation fails. 所以,如果事情是错误的(即从隐式类型转换
S*
到T*
是非法的,这恰好如果T
既不是S
,也不是一个基类的S
),编译失败。 Otherwise, the quality of the resulting machine code is not affected since the optimizer will detect the nonreachable code and remove it silently. 否则,生成的机器代码的质量不会受到影响,因为优化器将检测到无法访问的代码并以静默方式将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.