I've read this link: What is the correct way of using C++11's range-based for?, I've known why we use auto &&
to loop a vector<bool>
. But I still have one more question about auto &
and auto &&
.
class Test {};
vector<Test> vec = {Test{}, Test{}, Test{}};
vector<Test> vec2;
// case 1
for (auto &element : vec) {
vec2.emplace_back(element);
}
// case 2
for (auto &element : vec) {
vec2.emplace_back(std::move(element));
}
// case 3
for (auto &&element : vec) {
vec2.emplace_back(element);
}
// case 4
for (auto &&element : vec) {
vec2.emplace_back(std::move(element));
}
As you see, I'm trying to insert the objects from the vec
into the vec2
with the method move constructor of the class Test
.
I don't know which case I should use, which case is better, which cases are wrong.
Ofc, you might say that we can simply do vec2 = std::move(vec);
, this is correct but I want to know how to move-construct each element in a for loop, instead of move-construct the container.
Unless there's a specific reason to write your own loop, I'd say none of the above. Instead, I'd use:
std::move(vec.begin(), vec.end(), std::back_inserter(vec2));
At least by my reading, this makes it fairly apparent both: