skip to content

In C++, what are the practical differences between an lvalue reference and a pointer?

level: juniorimportance: must knowfreq 85%

answer

  1. an alias, not an object
  2. bound once, at declaration
  3. no null, no reseat
  4. assignment writes through

basics

~20 s

A reference is an alias for an existing object: bound once at declaration, never reseated, never null in a valid program. A pointer is an object holding an address that can be null, reassigned and incremented.

solid answer

~50 s

A pointer is an object in its own right: it has its own address and size, can be null, can be reassigned to point elsewhere, supports arithmetic and can be const independently of its pointee. An lvalue reference is an alias: it must be initialized, it is bound for life, and assigning to it assigns *through* it to the referred object - `ref = b;` copies `b` into the original, it never reseats. A well-defined program has no null references, `sizeof(ref)` gives the size of the referred type, and the standard leaves unspecified whether a reference occupies storage at all. You also cannot form arrays of references, pointers to references or references to references. In an interface, `Point&` says "there is always an object", while `Point*` says "maybe none", which is why the choice is a contract, not syntax.

code

cpp · 20 lines
cpp
#include <cstdio>

struct Point { double x, y; };

int main() {
    Point a{1, 1}, b{7, 7};

    Point* ptr = &a;   // a pointer is an object holding an address
    ptr = &b;          // reseats: ptr now points at b, a is untouched

    Point& ref = a;    // a reference is another name for a; it must be bound here
    ref = b;           // NOT a reseat: copies b's value into a

    ptr->x = 9;        // changes b
    ref.y = 3;         // changes a

    std::printf("a=(%.0f,%.0f) b=(%.0f,%.0f)\n", a.x, a.y, b.x, b.y);
    std::printf("same size as Point: %d\n", sizeof(ref) == sizeof(Point));
    // Point& unbound;  // error: declaration of reference variable 'unbound' requires an initializer
}

go deeper

for a junior

Recall that a reference must be initialized, cannot be reseated, has no null state in a valid program, and that assigning to it assigns to the referred object.

for a middle

Explain that a reference is an alias rather than an object: sizeof and & apply to the referent, and arrays of or pointers to references do not exist.

for a senior

Show why null references only arise from undefined behaviour at binding time, and where a reference's always-present contract makes an interface clearer than a pointer.

for a principal

Decide whether out-parameters should be pointers for call-site visibility or references for non-nullability, and apply the rule consistently across the codebase.

## Two ways to refer to an object C++ gives you two built-in ways to reach an object indirectly. A **pointer** (`Point*`) is an object whose value is an address. An **lvalue reference** (`Point&`) is a declaration that introduces another name for an existing object - an **alias**. Most of the practical differences follow from that one distinction. | Property | `Point* p` | `Point& r` | |---|---|---| | Must be initialized | no (but should be) | yes - except parameters, return types, class members, `extern` declarations | | Can be null | yes, `nullptr` | not in a well-defined program | | Can be reseated | yes, `p = &other;` | never; `r = other;` assigns to the referent | | Arithmetic | yes, within an array | no | | `sizeof` | size of a pointer | size of `Point` | | Has its own address | yes, `&p` | `&r` is the address of the referent | | Arrays of / pointers to it | allowed | "no references to references, no arrays of references, and no pointers to references" | | Storage | an object with storage | unspecified whether it needs storage | ## The reseat trap The difference interviewers probe most is assignment: ```cpp Point a{1, 1}, b{7, 7}; Point& ref = a; ref = b; // copies b into a; ref still names a ``` Juniors often read `ref = b;` as "now ref refers to b". It does not: it calls `Point`'s copy assignment on `a`. Once bound, a reference refers to the same object until it goes out of scope. If you need to retarget, you need a pointer or `std::reference_wrapper`. ## "References can't be null" - precisely The standard says a reference shall be bound to a valid object, and its note explains that a null pointer value does not point to an object, so "a reference in a well-defined program cannot refer to such things". In practice, `Point& r = *ptr;` with a null `ptr` compiles and may even appear to work until `r` is used - but the program already had **undefined behaviour** at the binding. So the precise claim is: - a reference never needs a null check, because every way to create a null one is already undefined; - the obligation moves to whoever forms the reference from a pointer: check the pointer first. ## What the syntax hides Under the hood, a compiler usually implements a reference parameter or member as an address, and generated code for `void f(Point&)` and `void f(Point*)` is typically identical. That is an implementation detail; the language deliberately does not promise it. What the language does promise: 1. A reference parameter needs no `&` at the call site and no `*` or `->` in the body, so call sites look like pass-by-value. Some teams therefore require pointers for out-parameters to make mutation visible; others prefer references because they cannot be null. 2. A reference to const can bind to a temporary such as `Point{1, 2}`; a pointer cannot, because the built-in `&` cannot take the address of a prvalue. 3. Operators such as `operator[]`, `operator=` and `operator<<` return references precisely so that `v[i] = x;` and chaining work with value syntax. ## When to use which - Use a **reference** when there is always an object: in-out parameters (`void normalize(Point& p)`), read-only parameters of expensive types (`const Path&`), returning an element from a container accessor. - Use a **pointer** when "no object" is a valid state, when you must reseat, or when you need arithmetic over an array. - Use neither for **ownership**: owning raw pointers are replaced by smart pointers, which the ownership material covers. ## What a strong answer adds - `sizeof` and `&` apply to the referent, which shows a reference is not a separate object you can inspect. - References are bound once; there is no syntax to reseat one. - The null-reference myth is answered with "creating one is already undefined behaviour". - The choice between them is about what the interface promises: "always an object" versus "maybe none".

  • Can a C++ reference ever be null, and what happens if you dereference a null pointer to create one?
    Not in a well-defined program. The standard says a reference must be bound to a valid object and notes that a null pointer value does not point to one. `Point& r = *ptr;` with a null `ptr` compiles, but the binding itself is undefined behaviour, so any later null check on `&r` can be optimized away. Check the pointer before forming the reference.
  • Why do operator[] and operator= usually return references?
    So that the result is an lvalue naming the existing object. `v[i] = x;` must assign into the container's element, not into a copy, and `a = b = c;` chains because `operator=` returns `*this` as a `T&`. Returning by value would make assignment through `[]` silently modify a temporary.

  • ref = other; makes the reference refer to other from now on
  • A reference is just a pointer that is automatically dereferenced, so it can be null
  • sizeof a reference gives the size of a pointer
  • You can declare a reference and bind it later
  • A std::vector of Point& works like a vector of pointers