【问题标题】:What is the difference between "const int& jj" and "int& const jj"?“const int& jj”和“int& const jj”有什么区别?
【发布时间】:2017-01-30 13:48:45
【问题描述】:

我对这两个感到困惑。我知道 C++ 引用本质上是常量,一旦设置它们就不能更改为引用其他内容。

【问题讨论】:

  • 您的编译器是否接受第二种变体?
  • 请指定哪个编译器为您接受了第二个变体。
  • @HumamHelfawi 这根本不是重复的。该问题涉及const int &int const &,两者都是有效(和等效)形式。这个处理const int &和语法错误int & const
  • 是的,GCC 和 Clang 都不接受后者。
  • @username_4567 您至少应该在问题中说明这一点。如,询问后一个是否真的有效。这样一来,问题看起来好像您在发布之前没有自己研究过。

标签: c++ reference constants language-lawyer


【解决方案1】:

const int& 表示引用 const int。 (类似地,int& 表示引用非常量 int。)

int& const 字面意思是 const 引用(对非 const int),这在 C++ 中是无效的,因为引用本身不能是 const 限定的。

$8.3.2/1 References [dcl.ref]

Cv 限定的引用格式不正确,除非 cv 限定符 通过使用 typedef-name ([dcl.typedef], [temp.param]) 或 decltype-specifier ([dcl.type.simple]),在这种情况下 cv 限定符被忽略。

正如您所说,引用本质上是恒定的,一旦设置它们就不能更改为引用其他内容。 (我们不能在初始化后重新绑定引用。)这意味着引用总是“const”,那么 const 限定引用或 const 非限定引用实际上可能没有意义。

【讨论】:

    【解决方案2】:

    const 限定符应用于引用意味着您不能更改引用的值。例如:

    void foo(int& arg) {
       arg = 1; // OK. The value passed by a caller will be changed in-place.
    }
    
    void foo(const int& arg) {
       arg = 1; // Compilation error.
    }
    

    int& const jj 是编译错误。

    【讨论】:

      【解决方案3】:

      区别:

      const int& jj// means a reference to const int.
      
      int& const jj // ill formed code that should trigger a compiler error
      

      【讨论】:

        猜你喜欢
        • 2010-11-11
        • 1970-01-01
        • 1970-01-01
        • 2020-08-03
        相关资源
        最近更新 更多