Container that stores a mixture of base and derived objects?

前端 未结 4 1743
说谎
说谎 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<std::unique_ptr<IBase>> v;
    v.push_back(std::unique_ptr<IBase>(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.

    0 讨论(0)
  • 2021-01-07 04:24

    [http://www.boost.org/doc/libs/1_51_0/libs/ptr_container/doc/ptr_container.html](The Boost pointer container library) is made just for this.

    0 讨论(0)
  • 2021-01-07 04:31

    There is example with std::vector and std::shared_ptr. I think that's what you want.

    #include <iostream>
    #include <memory>
    #include <vector>
    
    class Base {
    public:
       virtual void foo() {
          std::cout << "base" << std::endl;
       }
    };
    
    class Derived : public Base {
       void foo() {
          std::cout << "derived" << std::endl;
       }
    };
    
    int main()
    {
       std::vector<std::shared_ptr<Base> > v;
       v.push_back(std::shared_ptr<Base>(new Base));
       v.push_back(std::shared_ptr<Base>(new Derived));
    
       for (auto it : v) {
          it->foo();
       }
    }
    
    0 讨论(0)
  • 2021-01-07 04:34

    If you want polymorphic behavior (and you do want it), then you must use pointers or references. That is well documented in many places.

    And since you cannot use containers of references, you have to use containers of pointers.

    Now, you can use any type of pointer you see fit: unique_ptr, shared_ptr or raw pointers.

    0 讨论(0)
提交回复
热议问题