Container that stores a mixture of base and derived objects?

前端 未结 4 1797
说谎
说谎 2021-01-07 03:51

What is the right thing to do? I know that if the container is of base class value type, then derived object stored is \'sliced\'. If container is of derived class type, the

4条回答
  •  半阙折子戏
    2021-01-07 04:23

    The most obvious solution would be to use std::unique_ptr:

    class IBase {};
    class Derived : virtual public IBase {};
    std::vector> v;
    v.push_back(std::unique_ptr(new Derived())); 
    

    You could use std::shared_ptr, but it's ownership semantics significantly change the program's behaviour, keeping the dynamically allocated objects alive alive until nobody holds references to them.

提交回复
热议问题