c++ data alignment /member order & inheritance

后端 未结 9 1519
礼貌的吻别
礼貌的吻别 2020-11-29 01:34

How do data members get aligned / ordered if inheritance / multiple inheritance is used? Is this compiler specific?

Is there a way to specify in a derived class how

相关标签:
9条回答
  • 2020-11-29 02:21

    As soon as your class is not POD (Plain old data) all bets are off. There are probably compiler-specific directives you can use to pack / align data.

    0 讨论(0)
  • 2020-11-29 02:22

    Compilers generally align data members in structs to allow for easy access. This means that data elements will normally start on word boundaries and it gaps will normally be left in a struct to ensure that word boundaries are not straddled.

    so

    struct foo
    {
        char a;
        int b;
        char c;
    }
    

    Will normally take up more than 6 bytes for a 32 bit machine

    The base class is normally layed out first and the derived class it layed out after the base class. This allows the address of the base class to equal the address of the derived class.

    In multiple inheritance there is an offset between the address of a class and the address of the second base class. >static_cast and dynamic_cast will calculate the offset. reinterpret_cast does not. C style casts do a static cast if possible otherwise a reinterpret cast.

    As others have mentioned, all this is compiler specific but the above should give you a rough guide of what normally happens.

    0 讨论(0)
  • 2020-11-29 02:24

    I can answer one of the questions.

    How do data members get aligned / ordered if inheritance / multiple inheritance is used?

    I've created a tool to visualize the memory layout of classes, stack frames of functions and other ABI information (Linux, GCC). You can look at the result for mysqlpp::Connection class (inherits OptionalExceptions) from MySQL++ library here.

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