C++关于右值赋值的一个问题?

#include <iostream>
#include <string>
using namespace std;

struct A {
    int a;
    string b;
};

int main()
{
    // 为什么这句不可以赋值
    A().a = 12;
    // 而这句可以?
    A().b = "abc";
    
    return 0;
}
阅读 1.6k
1 个回答

第一个是内置的赋值表达式,赋值表达式要求左侧是可修改的左值。现在左侧是 xvalue ,不是 lvalue ,于是错误。

第二个是一个函数调用(调用的是 std::basic_string::operater= ),使用函数调用的规则,而不是内置表达式的规则。

在调用成员函数的时候,是会认为函数有一个隐含参数(仅用于overload resolution),类型为该类的(cv-左/右值)引用。over.match.funcs#3

这个引用在绑定到对象的时候,有一个特殊规定(over.match.funcs#5):

...... For non-static member functions declared without a ref-qualifier, an additional rule applies:

  • even if the implicit object parameter is not const-qualified, an rvalue can be bound to the parameter as long as in all other respects the argument can be converted to the type of the implicit object parameter.

就是函数如果没有 ref-qualifier ,那么这个(左值)引用可以绑定到一个右值。于是第二个可以成功调用。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题