Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't C++ allow rebinding a reference?

Tags:

c++

Is it a problem to rebind a reference? I've searched this question on Google, but I can't find relevant answers to this question. What made the designers of C++ decided to make it that way?

like image 643
lqr Avatar asked Nov 20 '14 10:11

lqr


2 Answers

Stroustrup's The Design & Evolution of C++ answers most questions of this kind. In this case, see the section §3.7 References:

I had in the past been bitten by Algol68 references where r1=r2 can either assign through r1 to the object referred to or assign a new reference value to r1 (re-binding r1) depending on the type of r2. I wanted to avoid such problems in C++.
If you want to do more complicated pointer manipulation in C++, you can use pointers.

like image 187
Jonathan Wakely Avatar answered Oct 01 '22 13:10

Jonathan Wakely


References are useful because they don't support unsafe pointer arithmetic and will never be null. On the other hand, pointers can be rebound and can be placed in STL containers. A trade off with all these useful properties is std::reference_wrapper:

#include <functional>
#include <iostream>
#include <string>

int main() {
  std::string s1 = "my", s2 = "strings";

  auto r = std::ref(s1);  // bind

  // use r.get() to access the referenced object
  std::cout << '\'' << r.get() << "' has " << r.get().size() << " characters\n";

  r = s2;  // rebind

  // use the other object
  std::cout << '\'' << r.get() << "' has " << r.get().size() << " characters\n";
}
like image 41
Ayxan Haqverdili Avatar answered Oct 01 '22 11:10

Ayxan Haqverdili