引用是表示它们所引用的另一个对象的语言实体。非常量引用是左值,必须用左值初始化。它们可以像这样有用:
int& x=condition ? array[1] : array[2];
int& y=condition ? array[0] : array[3];
x+=y;
y=0;
当用作函数参数时,它们告诉调用者他必须传递一个可能被函数写入的左值:
void set1(int& x) { x=1; }
int foo;
set1(foo); // ok, foo is 1
set1(foo+1); // not OK, not lvalue
另一方面,常量引用可以绑定到右值。在函数参数中,它们通常用于避免过多的副本:
void niceness(std::string s); // the string would be copied by its copy-ctor
void niceness(const std::string& s); // the caller's string would be used
请注意,这可能会或可能不会产生更快的代码。
当在普通代码中使用 const 引用时,它们也可以绑定右值和as a special rule, they extend the lifetime of the object they are bound to。这是您在代码中看到的:
const double& d=1; // OK, bind a rvalue to a const-ref
double& d=1; // Bad, need lvalue
所有引用都是多态的,就像指针一样:
class A { virtual void f(); }
class B : public A { void f(); }
B b;
A& ar=b;
ar.f(); // calls B::f()
所有的引用都是像指针一样的别名:
int f(int& a, const int& b)
{
a=1;
return b;
}
int x;
f(x, 42); // ==42, foo=1
x=42;
f(x, x); // ==1 (not 42), foo=1