Why is this struct not standard-layout?
Asked Answered
S

1

5

A piece of code is worth a thousands words.

#include <iostream>
#include <type_traits>

using namespace std;

struct A
{
    int a;
};

struct B : A
{
    int b;
};

int main()
{
    cout << is_standard_layout<B>::value << endl; // output false! WHY?
    return 0; 
}
Study answered 16/12, 2012 at 10:32 Comment(0)
S
8

From the definition of standard layout classes (§9 Classes, paragraph 7)

[...]
* either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and
[...]

Both the most-derived class and its base have non-static data members in your case. So it's not standard layout.

Saddlery answered 16/12, 2012 at 10:39 Comment(4)
Which has the effect that B b; cout << ( reinterpret_cast<int*> ( &b ) == ( &b.b ) ) << endl; outputs false.Valdemar
@PeteKirkham: Is this relevant ? &b == &b.a should output true here.Rhiamon
@MatthieuM.: yes, I believe Pete's comment is relevant. His expression would have output true if B were standard layout.Saddlery
@Mat: My point was that the demonstration Pete got is that if it were standard layout then the address of the object would be equal to that of its first member. However because it's not standard layout there is no definition of what the first member is! Well, in this case, my definition "first object reached by depth-first inspection" is certainly as valid as Pete's "first object reached by breadth-first inspection". It's kinda moot really :xRhiamon

© 2022 - 2024 — McMap. All rights reserved.