Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't we have offsetof which works with all types (except types with virtual inheritance)?

Tags:

c++

Currently, offsetof works only with standard layout types. However, I've never understood this limit. Sure, for types with virtual inheritance, offsetof cannot work. But for types without virtual inheritance, it could. I know, the standard allows non-standard layout types to have differing offsets of members for each instance. But, I've never heard of any compiler implementations which uses this. Why would it do something like this?

All the compilers I know, for types without virtual inheritance, offsets of members are compile-time constants.

So the question is:

  • is there any compiler, for which offsets of members are not compile-time constants (for types without virtual inheritance)?
  • why doesn't the committee relax the requirements of offsetof?

(I've read a lot of related answers here in stackoverflow, and discussions of this at various places, but I haven't found the reason of this).

like image 900
geza Avatar asked Jan 29 '23 13:01

geza


2 Answers

The arbitrary nature of this restriction was discussed in July by the committee. It's not in the working paper yet, but I believe it will be relaxed (to this degree, at least) in C++20.

like image 131
Davis Herring Avatar answered Feb 05 '23 19:02

Davis Herring


Relax the requirements to what? offsetofis okay to use except when it gives incorrect results?

The way to access selected data members of a C++ object is with a pointer to data member.

like image 41
Pete Becker Avatar answered Feb 05 '23 19:02

Pete Becker