Retrieve data from heterogeneous std::list

前端 未结 4 1817
孤城傲影
孤城傲影 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:50

    I would redefine Base to have a virtual method to output the information:

    class Base {
        friend std::ostream & operator << (std::ostream &os, const Base &b) {
            b.print(os);
            return os;
        }
        virtual void print (std::ostream &os) const = 0;
    public:
        virtual ~Base () {}
    };
    

    You are then forced to implement a print method in each derived class. Your print loop would look like:

        for (any_list::iterator itr=l.begin();itr!= l.end();++itr)
            std::cout << **itr;
    

    Your list should avoid managing bare pointers, since you put yourself at risk of leaking memory. You can use a smart pointer instead:

    typedef std::list< std::unique_ptr > any_list;
    

    Since unique_ptr requires explicit construction from the pointer, your code that populates the list needs to be updated.

        l.push_back(std::unique_ptr(new Derived1));
        l.push_back(std::unique_ptr(new Derived2));
        l.push_back(std::unique_ptr(new Derived3));
    

提交回复
热议问题