3 ms·
But be careful about the lifetime of the object referenced! Just because its 'const' doesn't mean it cant go out of scope.
by JoeAltmaier 10y ago
But be careful about the lifetime of the object referenced! Just because its 'const' doesn't mean it cant go out of scope.
- avlasyuk 10y agoLocal const reference prolongs the object lifetime[1]. There shouldn't be any problems whenever you use it in a for loop. [1]: https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-th...
- dbaupp 10y agoThere definitely can be problems: the reference may escape the for loop, and the reference may be invalidated by a modification of the container (even for something "stable" like ordered_map, the referent may be removed).
- E6300 10y agoIf a pointer/reference escapes the loop you'll have problems whether the thing to the right of the colon is a reference or a copy. If it's a copy, the escaped reference will definitely be invalid once that iteration complete. If it's a reference, it will remain valid in more situations.
- gpderetta 10y agoreferences prolong the lifetime of temporaries. It wouldn't work in this case: vector<int> v =...; const auto& x = v[59]; v.clear(); // x is dangling