Is it safe to cast to a class that has the same data member layout, but a different implementation?

后端 未结 2 1740
暖寄归人
暖寄归人 2021-02-14 18:53

The first class will be used for private inheritance in order to ensure the exact same layout. This should make casting safe.

#include 
#include          


        
2条回答
  •  逝去的感伤
    2021-02-14 19:48

    From [expr.reinterpret.cast]/11 in the language spec, you can cast a reference from one type to another (if you can cast a pointer to one to the other).

    With your class layouts, both types have a common base class that holds all the data. The two derived types do not add any data members, nor do they add any virtual functions, so the object layout for both classes will be the same.

    So the usage is safe if you use reinterpret_cast.

    In this case, this is similar to casting to a reference the base class, then casting that reference to the other derived class.

提交回复
热议问题