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?
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 throughr1
to the object referred to or assign a new reference value tor1
(re-bindingr1
) depending on the type ofr2
. I wanted to avoid such problems in C++.
If you want to do more complicated pointer manipulation in C++, you can use pointers.
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With