Sam
Sam

Reputation: 729

Reference to a pointer

char *str = "Hello";

char *ptr = str;
char *&rptr = str;

What is the difference between ptr and rptr? I understand rptr is a reference to a pointer(in theory) but how does it differ in terms of implementation with ptr?

Are references in C++ implemented using pointers?

Upvotes: 23

Views: 31717

Answers (3)

sepp2k
sepp2k

Reputation: 370082

What is the difference between ptr and rptr?

If you do char *world = "World"; rptr = world; and then print str, it will print "World". If you do ptr = world; and then print str, it will print "Hello".

Upvotes: 17

stinky472
stinky472

Reputation: 6797

str stores the address (and therefore points) to a literal string, "Hello", which is stored somewhere in a read-only segment of memory.

ptr points to the same address as 'str'.

rptr basically points to 'str' (not to the same pointee as str, but to str itself). It might be unusual to use 'points to' for references but they're really very much like pointers themselves (in this case a pointer to a pointer) except with slight syntactical differences and the restriction that they cannot point to any other address during their lifetime.

It would be analogous to:

char** const rptr = &str;

Like a reference, rptr above cannot be assigned a new address (it cannot change what it's pointing to), but it can be free to change its pointee (which happens to be a pointer in this case to 'str').

*rptr = 0; // after this, str == 0

References are pretty much the same as a read-only pointer (not a mutable pointer to read-only pointee) only they don't require a dereferencing operator to get at the pointee (the referenced data):

char *str = "Hello";
char *&rptr = str;
rptr = 0; // after this, str == 0

The only difference from the above example with a read-only pointer to pointer is that we didn't have to use the operator*.

const references also have the unique property of being able to extend the lifetime of temporaries, but that's probably beyond the scope of the discussion.

Upvotes: 12

Kleist
Kleist

Reputation: 7985

Try this:

#include <iostream>
int main () {
    char *str1 = "Hello ";
    char *str2 = "World!";
    char *ptr = str1;
    char *&rptr = str1;
    rptr = str2;
    std::cout << ptr << str1 << std::endl;
}

It prints "Hello world!" because ptr is a char pointer pointing to the string literal "Hello ". rptr is a reference to a char pointer, so when you change it (the pointer, not the thing it points at.) you change str1. And thus ptr points to "Hello ". str1 points to "World!".

Upvotes: 5

Related Questions