[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [lmi] Request for review
From: |
Greg Chicares |
Subject: |
Re: [lmi] Request for review |
Date: |
Thu, 12 Jan 2017 11:12:11 +0000 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Icedove/45.5.1 |
On 2017-01-12 10:14, Greg Chicares wrote:
[...]
> Rule 1:
> - for(std::vector<T>::iterator ...
> + for(T& ...
> - for(std::vector<T>::const_iterator ...
> + for(T ... <-- if T is a builtin type
> + for(T const& ... <-- otherwise
[...]
> Rule 2:
> - for(std::vector<T>::iterator ...
> + for(auto& ...
> - for(std::vector<T>::const_iterator ...
> + for(auto const& ...
[...]
> Rule 3 (not recommended):
> - for(std::vector<T>::const_iterator ...
> + for(auto ... <-- if T is a builtin type
Also consider...
Rule 4: Always write ranged-for loops as 'for(auto& ...'. Rationale:
http://www.codesynthesis.com/~boris/blog/2012/05/16/cxx11-range-based-for-loop/
|
| std::vector<int> v = {1, 2, 3, 5, 7, 11};
| const std::vector<int> cv = {1, 2, 3, 5, 7, 11};
|
| for (auto x: v) // x is int
| for (auto x: cv) // x is int
Avoid 'auto x:' because it's incorrect if we do this:
for (auto x: v) {x += 3;}
| for (auto& x: v) // x is int&
| for (auto& x: cv) // x is const int&
Here's the real point: the compiler deduces 'const'. It costs typing and
thought to specify 'const', so we should never write 'const' because it
has no benefit. Except...
Counterargument: sometimes we really do want to treat a container as
const even if we could modify it.
std::vector<int> values = {1, 2, 3, 5, 7, 11}; // Not const.
int sum_of_squares = 0;
// for(std::vector::const_iterator ... is what we'd write in C++98.
// Therefore:
for(auto const& v: values) {sum_of_squares += v * v;}
// In this "Rule 4" alternative:
for(auto& v: values) {sum_of_squares += v * v;}
// if we make a mistake and accidentally modify 'v' in the loop_statement,
// then we get a surprise. We'd get a diagnostic instead with 'auto const&'.
IOW, writing the const in 'auto const&' says this is a nonmutating loop,
in much the same way that writing const at the end of member function
says it's not a mutator. Conclusion: Rule 2 is better than Rule 4.
- [lmi] Request for review, Greg Chicares, 2017/01/11
- Re: [lmi] Request for review, Vadim Zeitlin, 2017/01/11
- Re: [lmi] Request for review, Greg Chicares, 2017/01/11
- Re: [lmi] Request for review, Vadim Zeitlin, 2017/01/11
- Re: [lmi] Request for review, Greg Chicares, 2017/01/12
- Re: [lmi] Request for review,
Greg Chicares <=
- Re: [lmi] Request for review, Greg Chicares, 2017/01/12
- Re: [lmi] Request for review, Vadim Zeitlin, 2017/01/12
- Re: [lmi] Request for review, Greg Chicares, 2017/01/12
- Re: [lmi] Request for review, Vadim Zeitlin, 2017/01/12
- Re: [lmi] Request for review, Greg Chicares, 2017/01/12
- Re: [lmi] Request for review, Vadim Zeitlin, 2017/01/13