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 445
甜味超标
甜味超标 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:36

    Adding new data to the Descendent class will break Descendent[]'s interchangeability with Base[]. In order for some function to pretend an array of larger structures is an array of smaller but otherwise compatible structures, a new array would have to be prepared in which the extra bytes are sliced off, in which case it is impossible to define the behavior of the system. What happens if some pointers are sliced off? What happens if the state of these objects is supposed to change as part of the called procedure, and the actual objects to which they refer are not the originals?

    Otherwise, if no slicing occurs and a Base* to the Derived[] was ++ed, sizeof(Base) would be added to its binary value, and it would no longer point to a Base*. There is obviously no way to define the behavior of the system in that case either.

    Knowing that, using this idiom is NOT safe, even if the standard and the president and God define it as working. Any addition to Descendent breaks your code. Even if you add an assertion, there will be functions whose legitimacy depends on Base[] being interchangeable with Descendent[]. Whoever maintains your code will have to hunt down each of these cases and come up with an appropriate workaround. Factoring your program around this idiom to avoid these problems will probably not be worth the convenience.

提交回复
热议问题