Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

offsetof macro in c++

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

I’ve been looking for this code for several minutes and I still don’t understand what the const char volatile reference thing is, it’s giving me a headache.

#define offsetof(s,m) ((size_t)&(((s*)0)->m))

This one is pretty clear, does make sense and it works well, why is the other one being used by MSVC compiler.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If s::m is of a class type, it could overload operator&, so &(((s*)0)->m) would be the same as (((s*)0)->m).operator&(), which could do something unexpected.

To not use any custom operator&, it is cast to a const volatile char& first (which will have the same address). It needs to be both const and volatile because s::m might be const and/or volatile.

This is how std::addressof would have been implemented before C++11.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading