c++0x why are "auto" vars in Range-based for-loop passed to loop body as values, not references?
I had an bug cuz of this, and it made me wonder why it was designed that way. I feel that it would be better that auto something:container would produce references, not values. For eg:
int t[3]{11,22,33};
for(int& el:t2)
el*=2;
开发者_如何转开发
gives 22,44,66
int t[3]{11,22,33};
for(auto el:t2)
el*=2;
"does nothing".
auto
in the case you describe deduced that the type was int
. If you wanted to turn that into a reference you can use auto&
.
If the C++ compiler would use special rules just because it is in a for loop the rules would extremely confusing.
auto i = t[1];
is the same as
int i = t[1];
The same case here, if you want a reference you have to specify that you want a reference.
auto
always deduces a value type. This is the same mechanism as what happens in a template, such as template<typename F> void foo(T t)
.
精彩评论