I know ordinary std::vector::push_back()
will copy the object. I hope this code would only destruct a
only once, using std::move()
and A(A&&) noexcept
to avoid copying. But it doesn't seem to work.
Is there any way that I can construct an object before push_back()
and move it into a vector perfectly?
#include <iostream>
class A {
public:
A() { std::cout << "construct" << this << '\n'; }
A(A&&) noexcept { std::cout << "move" << this << "\n"; }
A(const A&) = delete;
~A() { std::cout << "destruct" << this << '\n'; }
};
std::vector<A> as;
void add(A&& a) {
std::cout << "add 1\n";
as.push_back(std::move(a));
std::cout << "add 2\n";
}
int main() {
add(A());
std::cout << "main2\n";
return 0;
}
Output:
construct0x16d20b1fb
add 1
move0x151e068b0
add 2
destruct0x16d20b1fb
main2
destruct0x151e068b0
I hope this code would only destruct a
only once, using std::move()
and A(A&&) noexcept
to avoid copying.