When S is a trivial subclass of T, is it safe to use an array of S where an array of T is expected?

后端 未结 5 443
甜味超标
甜味超标 2021-01-11 15:19

Consider the following declarations of a pair of related structs. The descendant class adds no member variables, and the only member function is a constructor that does noth

5条回答
  •  猫巷女王i
    2021-01-11 15:28

    BEWARE! While this is almost certainly true in your compiler, this is not guaranteed by the standard to work.

    At least add if (sizeof(Derived) != sizeof(Base)) logAndAbort("size mismatch between Derived and Base"); check.

    In case you were wondering, the compilers for which this is safe are one to one in which the size doesn't change. There was something left behind in the standard that allows derived classes to be non-contiguous with base classes. In all cases where this happens, the size must grow (for obvious reasons).

提交回复
热议问题