1
votes

I read a very nice article about POD, Trivial, Standard-layout classes. But I have a question for standard-layout classes' rule:

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

I wrote a source code:

#include <iostream>

struct A {
    int a;
};

struct B {
    int b;
};

struct C : A, B {
    int c;
};

int main() {
    C c = {}; // initialize C
    c.a = 0xffffffff;
    c.b = 0xeeeeeeee;
    c.c = 0xdddddddd;
    std::cout << std::hex << *(reinterpret_cast<int*>(&c)  ) << std::endl;
    std::cout << std::hex << *(reinterpret_cast<int*>(&c)+1) << std::endl;
    std::cout << std::hex << *(reinterpret_cast<int*>(&c)+2) << std::endl;
}

The result is:

ffffffff
eeeeeeee
dddddddd

I think it works very well. And using debugger in VS2015, it looks fine.

enter image description here

Then, why is there the restriction for having non-static members in the inherited standard-layout rules?

1
"I think it works very well" What do you mean by that?Lightness Races in Orbit
you are trying to disprove the standard with a single example that appears to "work well" in one particular compiler and running on one particular machine. That wont work. Anyhow I dont understand the question, as the quote merely defines what a standard layout class is but doesnt mention any restrictions463035818_is_not_a_number
Indeed this is a pretty vacuous question. It's like complaining that someone decided a "car" is defined by having three or four wheels, observing that they can still get to work on a bike. It just makes no sense.Lightness Races in Orbit
I meant datas of the structure C lying on the memory in a row.Seokmin Hong
"It behaves how I expected it to" is a possible outcome from undefined behaviour. The standard makes no guarantees about the behaviour staying that way.Caleth

1 Answers

8
votes

Keep reading:

Standard-layout classes are useful for communicating with code written in other programming languages.

The rule you cited requiresthat only one class in the object's inheritance heirarchy consists of data. Consequently, such a type is "easy" to use for communicating with code written in other programming languages which may implement inheritance very differently (or, like C, not at all).

The rule doesn't mean you can't have more complicated types, or that you can't use those types in various exotic and interesting ways; it just means that they won't be specifically called "standard layout" types, with the consequences that go along with not being in that category of type.