I have just learned that the result of the prefix increment operator in C++ is an lvalue. There are probably cases where this behavior helps the programmer be more effective, but I could not think of any. What are some idiomatic uses of this behavior of the prefix increment operator?
The reason prefix ++
returns an lvalue is orthogonality; I've not seen
any use for it that wouldn't qualify as obfuscation. But the question
is: what rules apply to cause an expression to be an lvalue. In C, the
basic rule is that expressions which modify one of their operands aren't
lvalues, but a number of people wanted to support things like:
T&
someFunction( T& lhs, T const& rhs )
{
// ...
return lhs = rhs;
}
This works for user defined types (because operator=
will be a member
function), and some members wanted to support it for built-in types as
well. So the basic rule became: if an operator required an lvalue
operand, which it modified, and the results of the operator were the
changed operand, then it is an lvalue. (Thus, while prefix ++
is an
lvalue, postfix isn't, because the results of the expression aren't the
changed operand.)
Personally, I'm not sure I agree. I have no problem with replacing the above with:
T&
someFunction( T& lhs, T const& rhs )
{
// ...
lhs = rhs;
return lhs;
}
which is how I'd write it in my own code. But given that the first
example is legal for user defined types (where operator=
returns
a T&
), and that a number of committee members did like it, it seems
logical to extend it to the built-in types, and the resulting rule is
coherent, even if no one ever actually has the occasion to use the
results of prefix ++
as an lvalue.
EDIT:
Just to make it clear: I asked this very question at one of the
meetings (when we were defining C++ 98), and this was the
response I got (from, if I recall correctly, Andy Koenig, who
worked with Stroustrup on the earliest implementations of C++).
It was also the justification for having the default
implementation of operator=
return a T&
rather than a
T const&
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With