Retrieve data from heterogeneous std::list

前端 未结 4 1806
孤城傲影
孤城傲影 2021-01-24 20:14

In the below code I am simply trying to experiment with a Heterogeneous std::list where I have stored three Derived class object in a list of type Base*. When retrieving data fr

4条回答
  •  梦谈多话
    2021-01-24 20:30

    Your cast (Derived1*)*itr is equivalent to a static_cast which states:

    If the prvalue of type “pointer to cv1 B” points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the result of the cast is undefined.

    So you have undefined behaviour because you are casting pointers that point at Derived2 and Derived3 objects to a Derived1*.

    The proper way to achieve this is to have std::string s; defined in Base and give it a constructor that takes a std::string argument. Then you can make the constructors of Derived1 to Derived3 call this constructor with the appropriate string argument.

    If you add any extra members to one of the Derived classes, you won't be able to access them through the polymorphic Base*. However, trying to do that is a sign of bad design. You should only be treating the objects that a Base* points at as though they were Base objects. That is, Base describes the interface for those objects.

    If you really need to do something that is derived class specific to an object pointed to a Base*, you can use a dynamic_cast:

    if (Derived1* p = dynamic_cast(*itr)) {
      // This condition will only be true if the object pointed to by `*itr` really is a Derived1
    }
    

提交回复
热议问题