C++ POD struct inheritance? Are there any guarantees about the memory layout of derived members

后端 未结 3 1250
时光说笑
时光说笑 2020-12-10 01:18

Let\'s say, I have a struct RGB and I want to create struct RGBA, which inherits RGB:

struct RGB {
    unsigned char r         


        
相关标签:
3条回答
  • 2020-12-10 01:26

    There is NO guarantees about the memory layout of derived members and the cast is NOT safe.

    As you have inheritance, also there could be padding, this is NOT trivial.

    § 9 Classes

    1 A POD struct109 is a class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). Similarly, a POD union is a union that is both a trivial class and a standard layout class, and has no non-

    Also std::is_pod<RGBA> is not a POD

    std::cout << std::boolalpha;
    std::cout << std::is_pod<RGBA>::value << '\n';
    

    result is false. see live demo

    0 讨论(0)
  • 2020-12-10 01:32

    It's easy to check for padding: Print sizeof(RGB) and sizeof(RGBA). If it's not 3 respective 4 then the structures are padded, and you need to remove it.

    As for if the member a comes after b, you can use offsetof to check each members offset. If the offset for a is one larger than the offset of b then a comes directly after b.

    0 讨论(0)
  • 2020-12-10 01:34

    No, the layout is not guaranteed. The only guarantees are for standard-layout classes; and one of the conditions of such a class is that it

    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

    In other words, all data members must be in the same class, not in more than one.

    0 讨论(0)
提交回复
热议问题