About offsetof usage in C and C++?

我怕爱的太早我们不能终老 提交于 2019-12-10 19:53:51

问题


In C, I saw some usage of offsetof to calculate the offset of a member in the structure to its beginning?

Is it still recommended to use in C++? Any other way to do this without this macro?


回答1:


C++ has pointers to members. These are similar to offsets, but (1) typesafe and (2) more generic - they also work with methods, on base classes, etc.




回答2:


Offsetof is a feature that is only in the C++ standard for C compatibility so it is not reccomended to be used in C word




回答3:


I wouldn't recommend it for anything, unless you really need to. So long as your use is valid in C, it should be valid for C++. Without knowing what you are doing, your question is impossible to answer.




回答4:


No, it's not.

Proper C++ style encourages user to avoid all low-level details when possible. This is both for safety/correctness and readability. Only when low-level manipulation guarantees real and significant performance improve should one jump into it.




回答5:


One of the usages of offsetof() was in C-like code having structures with a fixed header, and variable size arrays, like explained in this blog post:

Why do some structures end with an array of size 1?

(Note that this blog post uses the FIELD_OFFSET macro, which is a Windows-ism, corresponding to offsetof().)

I think in modern C++ we should use higher-level techniques and code, like std::vector for variable sized arrays.



来源:https://stackoverflow.com/questions/22716560/about-offsetof-usage-in-c-and-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!