LoginSignup
1
1

More than 5 years have passed since last update.

[C++] Rebinding a reference is not allowed

Last updated at Posted at 2016-12-14

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
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1