Why are references not reseatable in C++
The reason that C++ does not allow you to rebind references is given in Stroustrup's "Design and Evolution of C++" :
It is not possible to change what a reference refers to after initialization. That is, once a C++ reference is initialized it cannot be made to refer to a different object later; it cannot be re-bound. 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++.
Can somebody explain to me what is reference reseating, and why is it not possible for a reference to point(refer) to another object?
y=z; //valid?
Absolutely! However, it does not mean "y
refers to z
from now on". It means "set the value of z
to whatever y
is currently referring", which is x
. Hence, y=z
is another way of writing x=z
.
Below is the C code regarding pointer reseating and it seems valid, am I right?
Unlike references, pointers can be re-pointed, so the re-assignment of the pointer makes it point to a different variable. Your program does not illustrate this, however, because two assignments to ptr
happen without any reads of ptr
in between, so only the second assignment stays.
Reseating a reference in C++. How the code does compiles?
As you say, references are not reseatable. What's happening is that the reference (which refers to a1
) is being assigned the value in b
. After the assignment, both intref
and a1
will be equal to b
.
Why is it illegal/immoral to reseat a reference?
Because there is no syntax to do it:
int x = 0;
int y = 1;
int & r = x;
Now if I say:
r = y;
I assign the value of y to x. If I wanted to reseat I would need some special syntax:
r @= y; // maybe?
As the main reason for using references is as parameters and return types of functions, where this is not an issue, it didn't seem to C++'s designers that this was a path worth going down.
C++: Why do you need references when you have pointers?
Operator overloading. Using pointers for "passing via reference" would give you unacceptable syntax.
Why no const reference in C++ just like const pointer?
References in C++ differ from pointers in several essential ways. One of the difference is:
Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
It means Reference
are like similar (see the link at the end of this answer) to const pointer (not pointer to a const!) in C++...
int a = 5;
int& m = a; // Behaves similar to int * const m = &a;
// See the link at the bottom for the differences between const pointer and reference.
and hence, you can't change/rebind them to point to some other address. So, you don't need a explicit const
qualifier for a reference and that's why it is disallowed by the compiler.
See this link to learn Why are references not reseatable in C++?
. I have copied the accepted answer of the above link:
The reason that C++ does not allow you to rebind references is given in Stroustrup's "Design and Evolution of C++" :
It is not possible to change what a reference refers to after initialization. That is, once a C++ reference is initialized it cannot be made to refer to a different object later; it cannot be re-bound. 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++.
EDIT:
See this link for Difference between const pointer and reference?
(Thanks to @M.M for pointing out the ambiguity in my statement).
Contradicting definition of references
Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object, just with another name. ...
Notes are informal and usually should not to be interpreted as strict rules. If an interpretation contradicts with standard rules, then that interpretation is wrong.
References and objects are different kinds of entities. A reference is not an object distinct from the one that it names. It isn't possible to form a pointer to a reference. A "pointer to reference" isn't even a valid type category.
The note is trying to say that reference "is" the object which it names in the sense that using the reference is using the referred object.
I was thinking of confirming that whether or not references take any space
References take space or they don't take space. It's up to the language implementation to figure out whether it needs space in each case.
Standard quote:
[dcl.ref] It is unspecified whether or not a reference requires storage
Outside of standard specifications, if you want an example of reference using space, try adding a reference member to a class and you are very likely to observe that the size of the class increases.
since pointers take space then reference should also take space. ...
Pointers do take space in the abstract machine that the standard specifies. But if you never observe the storage, then it's entirely possible that the storage never exists in practice. A significant difference between references and pointers is that you cannot observe the storage of a reference directly.
Philosopher: "If a tree falls in an abstract machine and no one is around to observe it, does it have an effect?"
Optimiser: "Not if I can help it."
What does reference can never be made to refer to another object mean?
It means, given this code
int a;
int b;
int& ref = a;
that, once you've initialized ref
to refer to a
, there is no way you can make it refer to b
or any other variable.
Any change you make to the reference will reflect on the variable that you used to initialize it with. The reference (which itself is not even a proper object) stays intact.
Also, a reference is only usable as long as the object it refers to stays alive.
Why do references occupy memory when member of a class?
The C++ standard only defines the semantics of a reference, not how they are actually implemented. So all answers to this question are compiler-specific. A (silly, but compliant) compiler might choose to store all references on the hard-disk. It's just that it proved to be the most convenient/efficient to store a reference as a constant pointer for class members, and replace the occurence of the reference with the actual thing where possible.
As an example for a situation where it is impossible for the compiler to decide at compile time to which object a reference is bound, consider this:
#include <iostream>
bool func() {
int i;
std::cin >> i;
return i > 5;
}
int main() {
int a = 3, b = 4;
int& r = func() ? a : b;
std::cout << r;
}
So in general a program has to store some information about references at runtime, and sometimes, for special cases, it can prove at compile time what a reference is bound to.
Related Topics
How to Succinctly, Portably, and Thoroughly Seed the Mt19937 Prng
What Exactly Is a Reentrant Function
"\N" or '\N' or Std::Endl to Std::Cout
Why Is the Template Argument Deduction Not Working Here
Forward Declaration of a Typedef in C++
Undefined Symbol _Gxx_Personality_V0 on Link
How to Output a Character as an Integer Through Cout
Why Can't Simple Initialize (With Braces) 2D Std::Array
Differences Between C++ String == and Compare()
Correct Way of Declaring Pointer Variables in C/C++
Will Using Goto Leak Variables
C++ Code File Extension? Difference Between .Cc and .Cpp
#Include All .Cpp Files into a Single Compilation Unit
Atomic Double Floating Point or Sse/Avx Vector Load/Store on X86_64
Why Does Std::Cout Output Disappear Completely After Null Is Sent to It