2016-11-29 38 views
2

为什么下面的代码正确:分配的R值

struct A 
{ 
    A operator+(A const& elem) 
    { 
    return *this; 
    } 

    bool operator==(A const& elem) 
    { 
    return true; 
    } 

    operator bool() 
    { 
    return true; 
    } 
}; 


int main() 
{ 
    A a_1, a_2; 

    if(((a_1+a_2) = a_1)) 
    {} 
} 

在这里,我预计在if语句错误,因为a_1 + a_2是r值。通过int a_1, a_2;更换线A a_1, a_2;导致预期的错误:

error: expression is not assignable 
     if(((a_1+a_2) = a_1)) 
      ~~~~~~~~~^
1 error generated. 
+0

*巨大的*将您的问题减少到最小(但仍然是完整)的例子。 –

回答

1

由于该类A(a_1+a_2) = a_1只会被解析为在最后A::operator=(const A&)通话。即使a_1+a_2返回的是一个临时对象,调用它的成员函数仍然有效。

如果你想禁止临时对象的调用,你可以使用ref-qualified member functions(因为C++ 11),它可以用来区分被调用的对象是l值还是r值。例如

struct A 
{ 
    //... 
    A& operator=(const A&) && = delete; // prevent from calling with temporary objects 
    A& operator=(const A&) & = default; 
}; 
+0

提示“ref-qualified member functions”非常好 - 谢谢。 –