来自< stddef.h>的'offsetof'宏调用未定义的行为? [英] Does the 'offsetof' macro from <stddef.h> invoke undefined behaviour?

查看:358
本文介绍了来自< stddef.h>的'offsetof'宏调用未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSVC实现的示例:

Example from MSVC's implementation:

#define offsetof(s,m) \
    (size_t)&reinterpret_cast<const volatile char&>((((s *)0)->m))
//                                                   ^^^^^^^^^^^

可以看出,它解引用一个空指针,通常调用未定义的行为。

As can be seen, it dereferences a null pointer, which normally invokes undefined behaviour. Is this an exception to the rule or what is going on?

推荐答案

语言标准说未定义的行为时,任何给定的编译器可以定义行为。标准库中的实现代码通常依赖于它。所以有两个问题:

Where the language standard says "undefined behavior", any given compiler can define the behavior. Implementation code in the standard library typically relies on that. So there are two questions:

(1)代码UB是否与C ++标准相关?

(1) Is the code UB with respect to the C++ standard?

这是一个非常困难的问题,因为它是一个众所周知的几乎缺陷,C ++ 98/03标准从来没有说在规范文本,一般来说,它是UB解引用空指针。这是 typeid 的例外,其中不是 UB。

That's a really hard question, because it's a well known almost-defect that the C++98/03 standard never says right out in normative text that in general it's UB to dereference a nullpointer. It is implied by the exception for typeid, where it's not UB.

你可以肯定地说,它是UB使用非POD类型 offsetof

What you can say decidedly is that it's UB to use offsetof with a non-POD type.

(2)是关于它编写的编译器的代码UB?

(2) Is the code UB with respect to the compiler that it's written for?

否,当然不是。

编译器供应商给定编译器的代码可以使用该编译器的任何特性。

A compiler vendor's code for a given compiler can use any feature of that compiler.

hth。,

这篇关于来自&lt; stddef.h&gt;的'offsetof'宏调用未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆