Argument passing through auto in range based on
3 answers
Yes, you will receive a copy for each item you will not be with auto&
or auto&&
. This one is better understood with an example
struct MyClass {
MyClass() {}
MyClass(const MyClass&) {
cout << "copy ctor invoked" << endl;
}
};
int main(){
vector<MyClass> objects;
MyClass obj1;
objects.push_back(obj1); // Vector filling
cout << "------" << endl;
for (auto obj : objects) // Auto loop
{}
cout << "------" << endl;
for (auto& obj : objects)
{}
}
Output:
copy ctor invoked // Vector filling
------
copy ctor invoked // Auto loop
------
+4
source to share
As written, you will receive a copy for each item. To avoid getting a copy, use
for (auto&& obj: object) {
}
You can also use one of the other obvious options:
- Still a derived type, but explicitly use the link below
auto&
. - Be clear, but use the following link
const
:auto const&
. - In fact, you can also use the type:
MyClass&
orMyClass const&
.
+10
source to share
Simple answer: your intuition is correct and you get a copy.
The reason for this lies in the type inferred auto
. Scott Myers recently spoke at CppCon 2014 about this topic: https://www.youtube.com/watch?v=wQxj20X-tIU
+1
source to share