Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference - const pointer

Tags:

c++

reference

I have read in many places about references:

Reference is like a const pointer

Reference always refer to an object

Once initialised, a Reference cannot be reseated

I want to make myself clear on the last point. What does that mean?

I tried this code:

#include <iostream>
int main()
{
    int x = 5;
    int y = 8;

    int &rx = x;
    std::cout<<rx<<"\n";

    rx = y;    //Changing the reference rx to become alias of y
    std::cout<<rx<<"\n";
}

Output

5  
8

Then what does it mean by "References cannot be reseated"?

like image 758
cppcoder Avatar asked Jul 10 '12 08:07

cppcoder


People also ask

Is reference a const pointer?

A pointer in C++ is a variable that holds the memory address of another variable. A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable. Hence, a reference is similar to a const pointer.

Can references be const?

The grammar doesn't allow you to declare a “const reference” because a reference is inherently const . Once you bind a reference to refer to an object, you cannot bind it to refer to a different object.

Can you reference a pointer?

References to pointers can be declared in much the same way as references to objects. A reference to a pointer is a modifiable value that's used like a normal pointer.

Can a const be a pointer?

Constant pointers: In constant pointers, the pointer points to a fixed memory location, and the value at that location can be changed because it is a variable, but the pointer will always point to the same location because it is made constant here.


1 Answers

This line:

rx = y;

Does not make rx point to y. It makes the value of x (via the reference) become the value of y. See:

#include <iostream>

int main()
{
    int x = 5;
    int y = 8;

    int &rx = x;
    std::cout << rx <<"\n";

    // Updating the variable referenced by rx (x) to equal y
    rx = y;    
    std::cout << rx <<"\n";
    std::cout << x << "\n";
    std::cout << y << "\n";
}

Thus it is not possible to change what rx refers to after its initial assignment, but you can change the value of the thing being referenced.

A reference is therefore similar to a constant pointer (where the pointer address is the constant, not the value at that address) for the purposes of this example. However there are important differences, one good example (as pointed out by Damon) being that you can assign temporaries to local const references and the compiler will extend their lifetime to persist for the lifetime of the reference.

Considerable further detail on the differences between references and const pointers can be found in the answers to this SO post.

like image 157
Alex Wilson Avatar answered Sep 30 '22 09:09

Alex Wilson