How to store a vector of objects of an abstract class which are given by std::unique_ptr?

China☆狼群 提交于 2019-12-07 06:05:29

问题


I got a loop in which i use a function returning std::unique_ptr to an object of an abstract class. I want to store these objects into a std::vector via push_back. But since the objects are of abstract type i get the following error:

error: cannot allocate an object of abstract type

for the line

  cells.push_back(std::move(*cell));

where cells is a std::vector of the abstract type and cell is of type

std::unique_ptr<AbstractType>&& cell

(I actually pass cell to a handler class) I know that one can not instantiate an abstract type and as I'm understanding the std:move operator it need to instantiate the object somehow?

Can anybody help me how to manage the problem? Or should the function (not my part of the project) not return a unique pointer to an object of an abstract type?


回答1:


You can't store AbstractType elements directly on a std::vector. You can simply store the unique_ptrs themselves in a std::vector<std::unique_ptr<AbstractType>> with cells.push_back(std::move(cell)).



来源:https://stackoverflow.com/questions/12203878/how-to-store-a-vector-of-objects-of-an-abstract-class-which-are-given-by-stdun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!