Why does myClassObj ++++ not bring a compilation error: '++' needs an l-value just like the buildin type?

Why is myint ++++ compiling with VS2008 compiler and gcc 3.42 compiler? I expected the compiler to say that an lvalue is needed, see the example below.

struct MyInt { MyInt(int i):m_i(i){} MyInt& operator++() //return reference, return a lvalue { m_i += 1; return *this; } //operator++ need it operand to be a modifiable lvalue MyInt operator++(int)//return a copy, return a rvalue { MyInt tem(*this); ++(*this); return tem; } int m_i; }; int main() { //control: the buildin type int int i(0); ++++i; //compile ok //i++++; //compile error :'++' needs l-value, this is expected //compare MyInt myint(1); ++++myint;//compile ok myint++++;//expecting compiler say need lvalue , but compiled fine !? why ?? } 
+8
c ++ operator-overloading lvalue
source share
6 answers

No, overloaded operators are not operators - they are functions. Therefore, the GCC correctly accepts that.

myobj++++; equivalent to myobj.operator++(0).operator++(0); Disabling a member function (including an overloaded operator) on a temporary object of type class is allowed.

+8
source share

Since for user types operator overloads are literally just function calls and therefore obey the semantics of function calls.

+3
source share

If you want to emulate the built-in behavior, this is actually a very simple solution: enter the return value of const :

 MyInt const operator++(int) { … } 

A few years ago there was a discussion about whether user statements should accurately model inline behavior. I'm not sure that the school of thought currently has the upper hand, but making the return type operator++(int) const was a way to achieve this.

+2
source share

After all, MyInt::operator++(int) is another method. The same rules apply. Since you can call methods on rvalues, you can call operator++(int) on rvalues.

+1
source share

myint ++ returns something similar to MyInt (2). So this is similar to executing MyInt (2) ++. The temporary class is created in the operator ++ function, and you increase the temporary class. After returning it, it is deleted as soon as the next statement ends (here it is the second ++ operator).

+1
source share

The problem is that the requirements of the postincrement operator for integral types and for custom types are different. In particular, the custom postincrement operator, implemented as a member function, allows the use of r values.

If you executed the operator as a free function:

 MyInt operator++(MyInt [const][&] x, int) 

Then the requirements of this particular operator will be those that are extracted from the actual signature. If the first argument is accepted by the value, then it takes rvalues ​​directly, if it takes the const & argument, then it takes rvalues, if the copy constructor is available, if the argument is not accepted by the constant & , then this statement will require lvalues.

+1
source share

All Articles