skip to content

Lvalue References

A reference is an alias that must bind at once and can never be reseated, and a const reference binds to temporaries. Interviewers ask when to pass by reference or by value.

on this pageshow

explore

questions

6

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
open as a page

In C++, why can a const Point& parameter bind to a temporary while a Point& parameter cannot?

level: middleimportance: must knowfreq 70%

basics

~20 s

A non-const lvalue reference may bind only to a modifiable lvalue, because writing into a temporary that vanishes is almost always a mistake. A const lvalue reference may also bind to rvalues and to values needing a conversion, through a temporary.

open as a page

In C++, when should a read-only parameter be passed by value rather than by const reference?

level: middleimportance: must knowfreq 68%

basics

~20 s

Pass small, cheap-to-copy types such as int, double or a two-double Point by value; pass types whose copy is expensive, such as std::string or std::vector, by const reference. By-value parameters also cannot alias the caller's other arguments.

open as a page

In C++, why does a class with a reference data member lose its copy assignment operator?

level: middleimportance: should knowfreq 52%

basics

~20 s

Assignment would have to reseat the reference, which the language cannot do, so the implicitly declared copy and move assignment operators are defined as deleted. Copy construction still works; store a pointer or std::reference_wrapper to regain assignment.

open as a page

Why can't a C++ std::vector hold Point& elements, and what does std::reference_wrapper change?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Container elements must be objects, and a reference is not an object: an allocator for Point& would need pointers to references, which do not exist. std::reference_wrapper<Point> is a small copyable, assignable object that holds a reference and converts to Point&.

open as a page

For a C++ library's public API, what parameter-passing convention would you set for your team, and how would you handle optional and in-out parameters?

level: principalimportance: should knowfreq 40%

basics

~20 s

Classify each parameter by role: cheap inputs by value, expensive inputs by const&, in-out by non-const reference, optional inputs by pointer, outputs as return values, consumed values by value. Write it down and enforce it with review and lint checks.

open as a page