不要使用原始指针,std::unique_ptr像这样使用:
std::vector<std::unique_ptr<Fruit>> m_fruits;
而且由于您不能复制std::unique_ptr必须使用的构造 a emplace_back(尽管您可以使用push_backwith std::move)。
m_fruits.emplace_back(新梨());
m_fruits.emplace_back(新番茄());
编辑:
看起来如果需要重新分配内存并且无法重新分配内存,则使用std::vector<std::unique_ptr<T>>::emplace_backandnew可能会泄漏std::vector,我推荐的方法(直到 C++14 引入std::make_unique)是这样使用push_back的:
m_fruits.push_back(std::unique_ptr<Fruit>(new Pear()));
m_fruits.push_back(std::unique_ptr<Fruit>(new Tomato()));
或使用std::make_unique:
m_fruits.push_back(std::make_unique<Pear>());
m_fruits.push_back(std::make_unique<Tomato>());