DEV Community

Discussion on: Pointer vs Reference in C++: The Final Guide

Collapse
 
pauljlucas profile image
Paul J. Lucas

A pointer has its own memory address and size on the stack ...

Pointers can also exist in the heap:

int **p = new int*{};
Enter fullscreen mode Exit fullscreen mode

... whereas a reference shares the same memory address (with the original variable) ...

You need to be really precise with wording here. A reference has its own address in memory (just like a pointer) that's distinct from the referent's address, but C++ provides no syntax for accessing a reference's address. For example, in:

struct S {
    S( int &r ) : _r{ r } { }
    int &_r;
};
Enter fullscreen mode Exit fullscreen mode

the reference _r inside S definitely has its own memory with a unique address.

.... but also takes up some space on the stack.

References can also exist in the heap:

int i;
S *p = new S{ i };  // the int& inside S is in the heap
Enter fullscreen mode Exit fullscreen mode