为何选择int&amp;在C ++中不允许a = <value>?</value>

时间:2013-10-15 07:35:54

标签: c++ pass-by-reference

我正在阅读C ++中的引用。它说int& a = 5给出了编译时错误。

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

此时我很困惑。我无法理解它背后的逻辑。为什么不能改变存储中的内容?据我所知,根据C ++规则它是无效的,但为什么呢?

3 个答案:

答案 0 :(得分:6)

  

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

如果您希望a成为const值的引用,则必须将其声明为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

对于非const绑定:

int x = 1;
int &a = x;

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

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

int &&a = 123;

答案 1 :(得分:5)

int& a = 5;

为了使上述代码有效,int&需要绑定到由int表达式创建的5类型的临时对象。但是将int&绑定到临时性并没有吸引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 ++的创建者不允许temporaries绑定到非const引用的原因之一。

但是,你可以这样做:

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

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

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

希望有所帮助。


1。假设int&可以绑定到x创建的临时值。功能

答案 2 :(得分:0)

你能做的是

int b=5;
int &a=b;

const int& a = 5;