简体   繁体   中英

Why is there a rule for having non-static members in the inherited standard-layout rules?

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.

在此处输入图像描述

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM