Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 274
soriak Avatar asked Aug 30 '12 19:08

soriak


1 Answers

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)).

like image 186
R. Martinho Fernandes Avatar answered Nov 15 '22 12:11

R. Martinho Fernandes