3
class Foo {
    public:
        int a;
        int b;
};

Foo x;
bool sameAddress =  (void*)&x  ==  (void*)&(x.a);

I have not yet come across a compiler/architecture for which sameAddress is false, but I have only looked at about 6 different variants. Is this defined or undefined? Does it depend on whether std::is_standard_layout<Foo>::value is true (and/or other aspects of the class definition)? Does #pragma pack( push, 1 ) help in guaranteeing it?

jez
  • 14,867
  • 5
  • 37
  • 64
  • 1
    If the class has virtual functions, they are not same on some compilers. – Sprite Nov 22 '20 at 02:59
  • Or this? https://stackoverflow.com/q/9254605/7509065 – Joseph Sible-Reinstate Monica Nov 22 '20 at 03:03
  • 1
    I think your assumption is right. Having `std::is_standard_layout::value` being `true` guarantees it as per the standard. – aep Nov 22 '20 at 03:03
  • 1
    Yes, it depends on `std::is_standard_layout::value` being `true` - there is not a guarantee otherwise. No, pragmas will not help guaranteeing that (even igoring the fact that pragmas, by definition in the standard are implementation-defined (i.e. compiler specific)). `#pragma pack` (for compilers that support it) is only concerned with padding between members, not with repacking the structure to (say) move virtual function pointers around (having virtual functions is one condition for a `struct`/`class` type not being standard-layout). – Peter Nov 22 '20 at 03:10

0 Answers0