【问题标题】:error in attaching temporary to a reference to const [duplicate]将临时附加到对 const 的引用时出错 [重复]
【发布时间】:2011-08-29 14:23:18
【问题描述】:

可能重复:
typedef and containers of const pointers

为什么代码会发出错误?

int main()
{
  //test code
  typedef int& Ref_to_int;
  const Ref_to_int ref = 10; 
}

错误是:

错误:从“int”类型的临时变量中“int&”类型的非常量引用的初始化无效

我阅读了prolonging the lifetime of temporaries 上的帖子,其中说临时对象可以绑定到对 const 的引用。那为什么我的代码没有被编译?

【问题讨论】:

    标签: c++ reference constants temporary


    【解决方案1】:

    这里ref 的类型实际上是reference to int 而不是const reference to int。 const 限定符被忽略。

    $8.3.2 说

    Cv 限定引用格式错误,除非通过使用 typedef (7.1.3) 或模板类型参数 (14.3) 引入 cv 限定符,在这种情况下忽略 cv 限定符。

    const Ref_to_int ref; 等价于int& const ref; 而不是const int& ref

    【讨论】:

    • 或者换句话说,typedef 不是简单的文本替换...并且const 应该放在 之后,让人们不要忘记它.
    【解决方案2】:

    您不能向typedef 添加额外的说明符。它不像宏那样工作。

    你的代码是有效的

    int& const ref = 10;  // error
    

    这是无效的。

    【讨论】:

      【解决方案3】:

      const 与 typedef 混合使用并不符合您的想法;请参阅this question 了解更多信息。这两行是等价的:

      const Ref_to_int ref;
      int& const ref;
      

      您正在寻找:

      const int& ref;
      

      修复它的一种方法是将它包含在 typedef 本身中(尽管您可能应该重命名它):

      typedef const int& Ref_to_int;
      

      【讨论】:

      • 我认为这个问题是出于所有意图和目的,是您提到的问题的副本。
      • @Chris 好点;指针和引用之间的区别并不重要
      猜你喜欢
      • 2019-07-02
      • 2010-10-20
      • 2012-07-18
      • 2015-05-23
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      相关资源
      最近更新 更多