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

后端 未结 3 1260
时光说笑
时光说笑 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 is not a POD

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

    result is false. see live demo

提交回复
热议问题