I have a class Bar which stores objects derived from BarItem:
#include <list>
#include <memory>
class Bar {
public:
typedef std::shared_ptr<BarItem> item_ptr;
void add_item(item_ptr item) {
items_.push_back(item);
}
private:
std::list<item_ptr> items_;
};
I have another class Note which is a subclass of BarItem. Currently to add a copy of a Note object I am doing:
Bar my_bar;
Note my_note;
my_bar.add_item(Bar::item_ptr(new Note(my_note)));
Which is a bit ugly; I would like to know if there is a better way or a way to automate this?
You can’t actually avoid the copy (in C++11 you can make it a move), but you can “automate” it so you save a few keystrokes by overloading the
add_itemfunction for each type (that may be child ofBarItem).