An unique_ptr
cannot be pushed back into a std::vector
since it is non-copyable, unless std::move
is used. However, let F
be a function that returns a unique_ptr
, then the operation std::vector::push_back(F())
is allowed. There is an example below:
#include <iostream>
#include <vector>
#include <memory>
class A {
public:
int f() { return _f + 10; }
private:
int _f = 20;
};
std::unique_ptr<A> create() { return std::unique_ptr<A>(new A); }
int main() {
std::unique_ptr<A> p1(new A());
std::vector< std::unique_ptr<A> > v;
v.push_back(p1); // (1) This fails, should use std::move
v.push_back(create()); // (2) This doesn't fail, should use std::move?
return 0;
}
(2)
is allowed, but (1)
is not. Is this because the returned value is moved somehow implicitly?
In (2)
, is it actually necessary to use std::move
?
push_back
allows this behavior which is the part that can help people understand how they can implement and allow such code to work with their own APIs – Rickety