Re: lvalue required as increment operand -- why does the Standard
requires this for fundamental types only?
SG wrote:
On 2 Jul., 19:30, Pavel wrote:
What is the rationale for this lvalue requirement if there is one?
-----------------
int f1() { return 5; }
class Int {
public:
explicit Int(int i) : i_(i) {}
Int& operator++() { ++i_; return *this; }
private:
int i_;
};
Int f2() { return Int(5); }
int main(int, char *[]) {
//int i1 = ++f1(); (void)i1; // this does not compile
Int i2 = ++f2(); (void)i2; // this compiles fine
return 0;
Why do you even want the first one to compile? f1 simply returns a
value. If you want f1()+1 then write f1()+1.
Because in a generic algorithms, f()+1 and ++f() for some (class) types may not
be equivalent (in particular, f() + 1 is often slower than ++f() for class
types). I want my algo to compile on both fundamental and class types and do not
want to sacrifice performance on class types if I do not have to. An example of
a (class) type for which operator+(some_distance_type) and operator++() may have
different performance is a list iterator.
There is abolutely no
reason to support prefix ++ on things that don't refer to any object.
Thanks, I knew that already. This was not not my question. The question was
about the specific rationale for this decision of the Standard's authors.
Check the C++ standard w.r.t. the C++ object model and lvalue/rvalue
expressions. You'll see that an rvalue of type int does NOT refer to
an object whereas an rvalue of type Int _does_ refer to an object
because Int is a class type.
Thanks, but that was not my question. I know (or I believe I know) how the
observed behavior is compliant with the Standard. I am asking for a rationale.
Now, why does C++ allow you to invoke a
nonconst member function on a temporary object?
Thanks, it was not my question again.
Answer: Why not? It
may be useful. Whether you overloaded an operator or wrote a function
with some other name does not matter. Your overloaded operator++ could
have other side effects which would make ++f2() do something useful.
Cheers!
SG
Thanks,
-Pavel