Consider the following code:
struct A {
A& add( int i ) { return *this; }
};
A& operator+=( A& a, int i ) { return a; }
void f() {
A a1 = A().add( 1 ); // expr 1
A a2 = A() += 1; // expr 2
}
Both expressions 1 and 2 are accepted by VC. Expression 2 is rejected by GCC with "No viable overloaded '+='". However such an expression is accepted for operators taking a reference to constant object:
const A& operator+=( const A& a, int i ) { return a; }
Why does GCC force this temporary to be constant in the operator context when not in the method call context, and is this correct behavior?
A();
Creates temporary.
A& operator+=( A& a, int i ) { return a; }
temporary cannot be binded to reference
. MSVC accept this, since it's non-standard extension. Look at rvalue to lvalue conversion Visual Studio
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.