gpt4 book ai didi

c++ - 空指针的地址?

转载 作者:可可西里 更新时间:2023-11-01 16:52:49 24 4
gpt4 key购买 nike

我遇到了下面的宏

#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))

我有点无法理解这一点,因为在 C++ 中,当我尝试引用空指针时,我预计会出现意外行为……但它怎么会有地址呢? null 的地址是什么意思?

最佳答案

为了宏的目的:它假定在​​地址 0 处有一个 TYPE 类型的对象,并返回成员的地址,该地址实际上是该成员在结构中的偏移量。

This answer解释了为什么这是未定义的行为。我认为这是最重要的引述:

If E1 has the type “pointer to class X,” then the expression E1->E2 is converted to the equivalent form (*(E1)).E2; *(E1) will result in undefined behavior with a strict interpretation, and .E2 converts it to an rvalue, making it undefined behavior for the weak interpretation.

这里是这样的。尽管其他人认为这是有效的。重要的是要注意,这将在许多编译器上产生正确的结果。

关于c++ - 空指针的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7511211/

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