Modifying reference variables, not the variable they alias [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ Reference, change the refered variable
I know that references in c++ are just pointers that get dereferenced for you when you use them. This question is about how to access the underlying pointer and change it.
Consider this code:
int x;
int& x_ref = x; //now equivalent to x
int* x_ptr = &x; //stores address of x
int* x_ref_ptr = &x_ref; //ALSO stores address of x
int&* x_ref_ptr_ref = ???; //what would this mean?
I'm trying to change where a reference points after initialization. I have no concern for type safety or proper practices. Does the c++ language have any tool to let me accomplish this?

There is no pointer to reference, it's ill-formed. A reference is an alias to an object. How would a pointer to an alias work?
Also, it's a feature of the language that a reference can't be reseated. A reseatable reference is a pointer.

This is not possible by design. By using a reference instead of a pointer, you decide to never change its target after declaration, with all entailing drawbacks and advantages (one of which is its "automatic dereferencing". Read the Wikipedia entry on references carefully.
You will need to switch to pointers.

Related

Pointers vs references examples, which is better in what cases

I'm beggining my programming learning and currently i'm wondering of difrences between pointers and references in C++. For exapmle we can use pointer to return more then one value from function (because as far as i know return can only give us one value) so here is one feature that pointer give us, but probably we can make the same using references.
Now i have questions:
What are the most common and easy to undestand cases in which i
should use pointers and in which i shoud use references?
Which are better to use if I have to my program as safe and as fast as possible?
Thank you for all answers! I hope you'll help me learn and undesrtand every aspect of programming in C++ :)
A pointer is a variable that holds memory address of another variable. A pointer needs to be dereferenced with * operator to access the memory location it points to.
A reference variable is an alias, that is, another name for an already existing variable. A reference, like a pointer is also implemented by storing the address of an object.
A reference can be thought of as a constant pointer (not to be confused with a pointer to a constant value!) with automatic indirection, i.e the compiler will apply the * operator for you.
Differences :
Reassignment: A pointer can be re-assigned. This property is useful for implementation of data structures like linked list, tree, etc. See the following examples:
int x = 5;
int y = 6;
int *p;
p = &x;
p = &y;
On the other hand, a reference cannot be re-assigned, and must be assigned at initialization.
int x = 5;
int y = 6;
int &r = x;

Difference between defining different types of references in C++ [duplicate]

This question already has answers here:
Why is it illegal to take the address of an rvalue temporary?
(6 answers)
Closed 8 years ago.
In C++, why am I allowed to do:
const int& x = 2;
but not:
int& y = 2;
?
The latter gives me the compiler error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’.
To understand what is going on here you need to recall the meaning of having a reference variable: it is a variable that refers to some other value, which is stored in some other place in memory.
Now recall the difference between a const and a non-const reference: the latter refers to a modifiable place in memory, while the former refers to a non-modifiable one.
It should be clear now why you cannot initialize a modifiable reference with a literal: the compiler does not have a place in memory that could be modified through your non-const reference. When the reference is const, the compiler can provide such a place for you, in the same way that it does for string literals. Theoretically, it could have done the same thing for non-const references; however, doing so would very likely hide a coding error, so language designers decided against it.
Well, to put it simple, the constant "2" you are using doesn't really have its "own" memory region. It is therefore impossible to create a reference that point on this memory region.
These kind of special values also called "r-value" must be handled with r-value references or const references:
int&& x;
const int& x;

why a const references can point to constant while normal reference can not [duplicate]

This question already has answers here:
How come a non-const reference cannot bind to a temporary object?
(11 answers)
Closed 8 years ago.
In c++, a reference variable can refer to an object as below
int i;
int &ref = i;
BUT if we put "const" keyword it can take any value, may be some variable or constant value.
Could some one brief me on this?
Regards,
Abhineet
This is known as const-correctness.
The standard does not define any implicit conversions from cv-qualified to less qualified types, and references act mostly like pointers which can only be assigned once and dereference automatically(Though you cannot bind a non-const lvalue to a non-const reference).
Still, you can use const_cast to override the compiler. On your own head be it then.

c++ reference/pointer [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Difference between pointer variable and reference variable in C++
I saw this simple code the other day, and I consider myself a beginner with pointers, although I have about a year and half experience with c++. Anyways...
Whats the difference between
int a = 0;
int &b = a;
and
int a = 0
int *p = &a;
Obviously, p holds the address of a, but b is a reference to a, meaning I can change the value of a with b. But I can also do the same thing with p. So what are advantages or disadvantages?
A reference must always be initialized
A reference can't be null
Once initialized, a reference can't be changed to be an alias of a different object.
I think it comes down to how you plan to use the variables afterwards in your program. Both statements appear to do the same thing (in this limited scope).
The first approach seems to be (in my opinion) poor programming practice since it may not be obvious later in the program that changing the value of b also changes the value of a. In the second, at least it is known that p is a pointer, so you should expect the side effects that come with changing the value to which it points.

Why is it illegal/immoral to reseat a reference? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Why are references not reseatable in C++
I am trying to more or less swap two reference variables (as practice, I could have swapped the actual variables). I tried doing this by making a temporary variable and making one of the references equal the other, but this got shot down by the compiler. Here is an example:
void Foo()
{
//code
int& ref1 = a;
int& ref2 = b;
int temp;
temp = ref1;
ref1 = ref2;
ref2 = temp;
//or, better yet
std::swap(ref1, ref2);
}
I got an error, and looked on the faq lite. It details that they cannot be reseated, but does not explain why. Why?
Here is a link to the Faq Lite for reference (<---, get it?).
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.
A reference is an alias to object.
Alias can not be changed (we are not spies ;-)
Because references don't have an address of their own (if they do that is implementation dependent, and you can't access them with the & operator directly).
The & operator is used to get the address of the thing that the reference is referring to.
Whereas a pointer does have an address of its own and you can access it with the & operator.
int x = 4;
int *p = &x;
//p holds the address of x
//&p holds the address of p.
int &r = x;
//&r holds the address of x
And if something doesn't have an address of its own then it can't store a value inside of it. And if it can't store a value inside of it, then it can't be changed.
I think the parashift C++ FAQ on references says it best:
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. It is not a pointer to the
object, nor a copy of the object. It
is the object.
and again in FAQ 8.5 :
Unlike a pointer, once a reference is
bound to an object, it can not be
"reseated" to another object. The
reference itself isn't an object (it
has no identity; taking the address of
a reference gives you the address of
the referent; remember: the reference
is its referent).
Look at your code again:
temp = ref1;
ref2 = temp;
ref1 = ref2;
References are aliases. All operations that you do on the reference are performed on the object it references. In your code above, how should the compiler magically know that you aren't trying to assign the values to referenced variables, but are rather trying to change the reference itself? There's no syntax to indicate the difference between that, and, for example:
ref1 = 3;
which you'd normally expect to assign a value 3 to the object referenced by ref1.
In short, this is simply by design. If you want "reseatable" references, then you just use pointers (or, if you want to avoid accidential pointer arithmetic, boost::optional).
Unlike pointers, references are designed to guarantee that they always refer to an object. To meet this gaurantee, the compiler requires that all references be initialized in their declaration and disallows you from reassigning them.
Similar to pointers, reference variables allow you to access the same instance of an object through multiple locations - but unlike pointers, reference provide a greater level of safety.