c++/ gcc

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.

Related Question modification of ‘<temporary>’ is not a constant expression Is there a gcc warning for “conditional expression is constant”? GCC 4.7.1 generalized constant expression issue with overload gcc and clang disagree on whether expression is constant evaluated Is gcc considering builtins of non-constant expression functions to be constant expressions error “cannot appear in a constant-expression” in g++ but not in gcc Using function argument as part of a constant expression - gcc vs clang GCC: 'std::is_same_v<int, T>' is not usable in a constant expression Constant reference to temporary object constexpr initializer_list raising an error: "expression must have a constant value -- reference or pointer to temporary with limited lifetime"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM