0

For a type T and it's member variable m, the simplest form of offsetof(T, m) would be

&static_cast<T*>(0)->m

although it is clearly UB. Is there a way to do the same thing without involving UB on the assumption that T is either POD or non-POD but there is no virtual inheritance? Or alternatively, is there a way to ensure at compile time that under the current implementation (by which the code is being compiled) the expression is guaranteed to be evaluated to the correct value?

For now I'm using the above expression without any issues in the current versions of GCC, Clang and Visual C++, but it is being threatened by GCC's Undefined Behavior Sanitizer which has been enforced recently in our codebase.

Chungmin Lee
  • 2,320
  • 2
  • 18
  • 19
  • [Related](https://cplusplus.github.io/LWG/lwg-defects.html#2709). Presumably "conditionally-supported" here means "implementation-defined" which would silence UBsan. Until then you might be able to [manually suppress the error detection](http://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#suppressing-errors-in-recompiled-code-blacklist). – nwp Sep 15 '17 at 10:44
  • 3
    `offsetof` is part of the standard library **beacuse** it is not possible to portably implement it in user code. – Bo Persson Sep 15 '17 at 11:00
  • Note that, with virtual inheritance involved, base class subobject and its members may be located outside of the object itself - that is, at a negative offset or at an offset greater than the size of the object. It is generally impossible to compute the correct offset without actually having a live object in hand. – Igor Tandetnik Sep 15 '17 at 15:11
  • I know it doesn't work with virtual inheritance, but I can't think of a case with non-POD, no virtual inheritance. Even if future implementations of GCC optimize more aggresively, there must be a compiler error rather than a runtime error. – Chungmin Lee Sep 18 '17 at 03:00
  • If you're already OK with dirty hacks, consider forming a pointer-to-member and then inspecting its bits. – zwol Sep 18 '17 at 19:10

0 Answers0