As described in the title, c++ doesn't allow to rebind a reference. See some sample code.
int a = 1;
int b = 2;
int &ref = a;
ref = 5;
cout << a << " " << b << endl; // 5 2
ref = b;
ref = 6;
cout << a << " " << b << endl; // 6 2
We try to rebind the ref to variable b
and update the value of b
through reference. But it doesn't work.
Here is a explanation about this and very easy to understand.
Update
Thanks @l1048576 's comment. In C++11 there is a class std::reference_wrapper
that wraps a reference in a copyable, assignable object.
int a = 1;
int b = 2;
std::reference_wrapper<int> ref = a;
ref.get() = 3;
cout << a << " " << b << endl; // 3 2
ref = b;
ref.get() = 5;
cout << a << " " << b << endl; // 3 5