Getting error with list of key type std::unique_ptr

I have a Polymorphic class and some child classes, of which I need to make multiple instances of, using a list container. I've set the key type to be a unique pointer of the polymorphic class, and the values of each element pointing to a New Child instance, like so:

1
2
std::list<std::unique_ptr<Polymorphic>> polymorphic;
polymorphic.push_back(new Child(foo, bar));


The only problem is that when I try to push_back a new element, I get a compiler error, saying "No instance of overloaded function".

Should I try and create a pointer object on it's own and push back that object as an element, it will work fine:
1
2
3
4
std::unique_ptr<Polymorphic> polym(new Child(foo, bar));

std::list<std::unique_ptr<Polymorphic>> polymorphic;
polymorphic.push_back(polym);


Is there some way I can push a new Child instead of having to create a Polymorphic pointer object and pushing that?
Yes, use emplace_back instead.
1
2
3
polymorphic.emplace_back(new Child(foo, bar));
//or in C++14, exception safe
polymorphic.emplace_back(std::make_unique<child>(foo, bar));


BTW your second example invalid. unique_prt are not copyable, you have to move them in place: polymorphic.push_back(std::move(polym));
Last edited on
Should I try and create a pointer object on it's own and push back that object as an element

If you do it like that you will have to move the std::unique_ptr object because you can't copy a std::unique_ptr (if you could copy then it would no longer be unique).
1
2
3
4
std::unique_ptr<Polymorphic> polym(new Child(foo, bar));

std::list<std::unique_ptr<Polymorphic>> polymorphic;
polymorphic.push_back(std::move(polym));


You don't need to create the std::unique_ptr as a variable, if you just make sure to call the std::unique_ptr constructor explicitly.
 
polymorphic.push_back(std::unique_ptr<Polymorphic>(new Child(foo, bar)));


In C++14 you can also use the convenient std::make_unique function.
 
polymorphic.push_back(std::make_unique<Child>(foo, bar));
1
2
3
4
5
6
namespace cpp14 
{
    template< class T, typename... ARGS >
    std::unique_ptr<T> make_unique( ARGS&&... args )
    { return std::unique_ptr<T>( new T( std::forward<ARGS>(args)... ) ) ; }
}


And then:

1
2
3
4
5
6
using cpp14::make_unique ;

std::list<std::unique_ptr<Polymorphic>> polymorphic;

// polymorphic.push_back(new Child(foo, bar));
polymorphic.push_back( make_unique<Child>(foo, bar) );
Cheers guys, thanks for the help! Much obliged.
Topic archived. No new replies allowed.