Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move item to a list without copying

Given

std::list<std::vector<float>> foo;
std::vector<float> bar;

How should I move bar to the end of foo without copying data?

Is this ok?

foo.emplace_back(std::move(bar));
like image 748
ChronoTrigger Avatar asked Jan 16 '17 10:01

ChronoTrigger


3 Answers

Is this ok?

foo.emplace_back(std::move(bar));

Yes, because:

  1. std::move(bar) casts bar to an rvalue reference.

  2. std::list::emplace_back takes any number of forwarding references and uses them to construct an element at the end.

  3. std::vector::vector has an overload (6) that takes an rvalue reference, which moves the contents of the rhs vector without performing any copy.

like image 123
Vittorio Romeo Avatar answered Nov 12 '22 10:11

Vittorio Romeo


Yes, the code in the Q is certainly OK. Even using push_back would be OK:

foo.push_back(std::move(bar));
like image 40
Angew is no longer proud of SO Avatar answered Nov 12 '22 11:11

Angew is no longer proud of SO


How should I move bar to the end of foo without copying data?

Using the move constructor of std::vector:

foo.push_back(std::move(bar));

Is this ok?

foo.emplace_back(std::move(bar));

That is OK as well.

like image 5
eerorika Avatar answered Nov 12 '22 10:11

eerorika