【问题标题】:Passing arguments as const reference vs normal reference [duplicate]将参数作为常量引用与普通引用传递[重复]
【发布时间】:2011-12-16 16:13:21
【问题描述】:

可能重复:
How come a non-const reference cannot bind to a temporary object?

有这样的代码:

void fun_ref(int& par){}

void fun_const_ref(const int& par){}

int main(){

  //fun_ref(2); error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’
  fun_const_ref(2);

  char var = 3;
  //fun_ref(var); error: invalid initialization of reference of type ‘int&’ from expression of type ‘char’
  fun_const_ref(var);
  return 0;
}

为什么常量引用可以传递右值和与函数参数类型不同的数据类型,而非常量引用却不行?

【问题讨论】:

    标签: c++


    【解决方案1】:

    编译器可以通过隐式转换创建函数参数类型的临时变量,并将其作为 const 引用传递。这不适用于引用类型,因为临时对象不能作为非常量引用传递。

    编辑:不允许对临时对象进行非常量引用,因为标准是这样说的。这背后的原因是,获取非 const 引用的函数将更改其参数(否则您可以将引用设为 const),并且当临时超出范围时,这些更改将丢失。

    【讨论】:

    • 对,那个,问题是为什么不能将临时对象作为非常量引用传递?
    【解决方案2】:

    当参数是 const 引用并且传递的参数不是该类型但存在到该类型的隐式转换时,实现会将值保存在临时文件中并使用该临时文件作为参数。所以 const 版本没有引用char var,而是引用int __temp

    【讨论】:

      【解决方案3】:

      在第一种情况下,2 是临时的,因此它只能绑定到 const 引用;这就是为什么你不能用它打电话给fun_ref

      在第二种情况下,varchar,因此它不能绑定到 int&。但是,var 可以转换为临时的int,可以像上面那样绑定到const int&;由于隐含的覆盖,它可以工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-15
        • 1970-01-01
        • 2017-03-21
        • 2017-02-24
        • 2015-09-16
        • 2023-04-05
        • 1970-01-01
        相关资源
        最近更新 更多