Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ no matching function for call to vector push_back [duplicate]

Tags:

c++

c++11

I have a vector like this:

std::vector<std::unique_ptr<Service> > m_vec;

I can run push_back like this:

m_vec.push_back(std::make_unique<Service>());

But when I run it like this:

std::unique_ptr<Service> pt = std::make_unique<Service>();
m_vec.push_back(pt);

I got error no matching function for call to ‘std::vector<std::unique_ptr<Service> >::push_back(std::unique_ptr<Service>&)

Does & mean that I'm pushing a reference to the vector? If so, why can't I push a reference?

like image 672
user4016367 Avatar asked Mar 12 '23 14:03

user4016367


2 Answers

std::unique_ptr couldn't be copied, only can be moved.

The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

std::make_unique<Service>() is a temporary variable and could be taken as rvalue and to be moved, but you can not do the same thing with a named variable. You can use std::move:

std::move is used to indicate that an object t may be "moved from"

Such as,

m_vec.push_back(std::move(pt));
like image 193
songyuanyao Avatar answered Apr 30 '23 21:04

songyuanyao


what you want is

std::unique_ptr<Service> pt = std::make_unique<Service>();
m_vec.emplace_back(std::move(pt));

you cannot copy unique_ptr, since they are unique. you can create one and then move it around. emplace_back will make sure that no temporeries are made, and the element is constructed in-place(without copies, temporeries etc.)

like image 26
David Haim Avatar answered Apr 30 '23 21:04

David Haim