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 446
甜味超标
甜味超标 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条回答
  •  情书的邮戳
    2021-01-11 15:45

    While this particular example is safe on all modern platforms and compilers I am familiar with, it is not safe in general and it is an example of a bad code.

    1. It cannot work on compilers/platforms where sizeof(Base) != sizeof(Descendant)
    2. It is unsafe because someday someone in your project will add a new non-static member to the Descendant class or will make the Base class virtual.

    UPD. Both Base and Descendant are standard layout types. So it is a requirement of the standard that a pointer to Descendant can be correctly reinterpret_cast to a pointer to Base, that means no padding in front of the structure is allowed. But there is no any requirement in C++ standard for padding at the end of a structure, so it is compiler-dependent. There is also the standard proposal to explicitly mark this behavior as undefined. http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1504

提交回复
热议问题