简体   繁体   English

以下代码如何工作?

[英]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.

相关问题 以下代码不起作用 - The following code does not work 以下程序如何工作? - How does following program work? 字节顺序测试:为什么以下代码有效? - Testing for Endianness: Why does the following code work? 为什么下面的代码在Windows XP中不能运行,而在Windows 7中却不能运行? - Why does the following code work in Windows XP but not 7? 以下代码如何为唯一的调用堆栈每次都唯一地实例化模板函数? - How does the following code work to uniquely instantiate a template function everytime for a unique call-stack? 以下前向声明的多继承指针转换的代码如何工作? - How does the following foward-declared multi-inheritance pointer converted code work? 由于return语句中使用了布尔OR操作,因此递归如何对以下代码起作用? - How does recursion work for the following code, since a Boolean OR operation is used in the return statement? 如何在以下c ++代码中基于返回类型进行运算符重载解析 - how does operator overload resolution work based on return type in the following code of c++ function 过载在以下情况下如何工作? - How does function overloading work in the following case? structname &amp;function 在下面的例子中是如何工作的? - How does structname &function work in the following example?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM