问答

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

作者:admin 2021-06-16 我要评论

#include iostream#include stringusing namespace std;struct A { int a; string b;};int main(){ // 为什么这句不可以赋值 A().a = 12; // 而这句可以? A().b...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)
#include <iostream>
#include <string>
using namespace std;

struct A {
    int a;
    string b;
};

int main()
{
    // 为什么这句不可以赋值
    A().a = 12;
    // 而这句可以?
    A().b = "abc";
    
    return 0;
}
###

第一个是内置的赋值表达式,赋值表达式要求左侧是可修改的左值。现在左侧是 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 ,那么这个(左值)引用可以绑定到一个右值。于是第二个可以成功调用。

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • C++关于右值赋值的一个问题?

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

  • SpringBoot:默认情况下NotReadableExce

    SpringBoot:默认情况下NotReadableExce

  • vue typescript 引入vue-meta报错?

    vue typescript 引入vue-meta报错?

  • html+css3动画 服务端(node.js)转成

    html+css3动画 服务端(node.js)转成

腾讯云代理商
海外云服务器