lundi 26 avril 2021

auto & vs auto &&: Which one should we use in a for loop

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 &it : vec) {
    vec2.emplace_back(it);
}
// case 2
for (auto &it : vec) {
    vec2.emplace_back(std::move(it));
}
// case 3
for (auto &&it : vec) {
    vec2.emplace_back(it);
}
// case 4
for (auto &&it : vec) {
    vec2.emplace_back(std::move(it));
}

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.

Aucun commentaire:

Enregistrer un commentaire