这是有效的 ANSI C++ 代码吗?试图在编译时生成结构成员的偏移量 [英] Is this valid ANSI C++ code? Trying to generate offsets of structure members at compile-time
问题描述
可能的重复:
是否来自
取消引用空指针
#define _OFFS_OF_MEMBER(p_type, p_member) (size_t)&(((p_type *)NULL)->p_member)
struct a
{
int a, b;
};
size_t l = _OFFS_OF_MEMBER(struct a, b);
我与一些其他用户进行了一些聊天/对话,其中一个人说这是取消引用并访问地址 NULL 附近的地址空间.我说:获取成员的地址不会访问、触摸或读取该成员的值.根据标准,它是完全安全的.
I had a little chat/conversation with some fellow users, and one of them said that this is dereferencing and accessing the address space near address NULL. I said: taking an address of a member will not access, touch, or read the value of that member. According to standard it is completely safe.
struct a* p = NULL;
size_t offset = &p->b; // this may NOT touch b, it is not dereferencing
// p->b = 0; // now, we are dereferincing: acccess violation time!
这是否始终是计算偏移量的安全方法,还是编译器可以根据标准自由取消引用并弄乱地址 NULL 附近的内存?
Is this always a safe way to calculate offset, or are compilers free to dereference and mess up the memory near address NULL according to standards?
我知道有一种安全的方法可以计算标准提供的偏移量,但我很好奇您对此有何看法.都赞成我的解释:对这个问题投赞成票 :-)
I know there is a safe way to calculate offsets provided by the standard, but I am curious what you have to say about this. All in favor of my explenation: up-vote this question :-)
推荐答案
这里没有取消引用任何无效的内容.该宏所做的只是告诉编译器在地址 NULL
处的内存中存在 p_type
类型的结构.然后它获取p_member
的地址,它是这个虚构结构的成员.所以,不要在任何地方取消引用.
You're not dereferencing anything invalid here. All that macro does is tell the compiler that a structure of type p_type
exists in memory at the address NULL
. It then takes the address of p_member
, which is a member of this fictitious structure. So, no dereferencing anywhere.
事实上,这正是offsetof
宏,定义在 stddef.h
中.
正如一些评论所说,这可能不适用于 C++ 和继承,我只将 offsetof
与 C 中的 POD 结构一起使用.
As some of the comments say, this may not work well with C++ and inheritance, I've only used offsetof
with POD structures in C.
这篇关于这是有效的 ANSI C++ 代码吗?试图在编译时生成结构成员的偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!