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?
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));
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With