【问题标题】:Why int& a = <value> is not allowed in C++?为什么 C++ 中不允许使用 int& a = <value>?
【发布时间】:2013-10-15 07:35:53
【问题描述】:

我正在阅读 C++ 中的参考资料。它说int&amp; a = 5 给出了编译时错误。

Thinking in C++ - Bruce Eckel中,作者说编译器必须首先为 int 分配存储空间并生成绑定到引用的地址。存储必须const,因为改变它没有意义

在这一点上我很困惑。我无法理解其背后的逻辑。为什么不能更改存储中的内容?我知道根据 C++ 规则它是无效的,但是为什么呢?

【问题讨论】:

标签: c++ pass-by-reference


【解决方案1】:

“存储必须是 const,因为更改它没有意义。”

如果您希望a 引用一个常量值,您必须将其声明为const,因为a 引用的是一个临时常量值,并且无法更改它。

const int &a = 123;
a = 1000; // `a` is referencing to temporary 123, it is not possible to change it
          // We can not change 123 to 1000
          // Infact, we can change a variable which its value is 123 to 1000
          // Here `a` is not a normal variable, it's a reference to a const
          // Generally, `int &a` can not bind to a temporary object

对于非常量绑定:

int x = 1;
int &a = x;

a 是对左值的引用。简单来说,它是另一个变量的别名,所以在右手边你应该给一个变量。引用a 在第一次绑定后不能更改并绑定到另一个变量;

在 C++11 中,您可以通过右值引用来引用临时对象/值:

int &&a = 123;

【讨论】:

    【解决方案2】:
    int& a = 5;
    

    为了使上述代码能够工作,int&amp; 需要绑定到由表达式 5 创建的 int 类型的临时对象。但是将int&amp; 绑定到临时文件并没有吸引 Bjarne Stroustrup — 他举了一个类似于以下内容的示例来说明他的观点:

    void f(int &i) { ++i; }
    
    float x = 10.0;
    f(x); 
    std::cout << x <<< std::endl;
    

    std::cout 会打印什么1?看起来它会打印11

    感觉++i 正在更改参数 x,但它没有。这就是 C++ 的创建者不允许临时对象绑定到非常量引用的原因之一。

    但是,您可以这样做:

    int const & i = 10;
    int const & j = x; //x is float
    

    从 C++11 开始,您可以这样做:

    int && i = 10;
    int && i = x; //x is float
    

    希望对您有所帮助。


    1.假设int&amp; 可以绑定到由x 创建的临时对象。

    【讨论】:

    • +1 表示f() 示例:THIS。我偶尔想知道为什么 l-refs 不能自己绑定到临时对象,但从未想过那个。谢谢你拓宽了我的视野:-)
    • 感谢您的回复。因此,我从您的回答中得出的结论是,Bjarne Stroustrup 就是这样做的。我只是想确保我没有遗漏整个概念背后的一些逻辑!
    【解决方案3】:

    你能做的是

    int b=5;
    int &a=b;
    

    const int& a = 5;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 2013-04-11
      相关资源
      最近更新 更多