Pointers vs References in C++: Semantics and API Design
Data Structure DesignModel answerLast updated
Contrast C++ raw pointers with references, choose the right parameter and return types for four trading-engine APIs, and explain how aliasing affects optimization.
Context
You are building part of a low-latency order-handling engine in C++. In this kind of code, the choice between a pointer and a reference is a design decision. It communicates who owns an object, whether it may be absent, how long it stays valid, and what the optimizer is allowed to assume.
Answer the three parts below as you would in a technical discussion.
Part 1: Mechanics
Compare raw pointers (T*) and lvalue references (T&) along these axes:
- Initialization and nullability: what must happen at declaration, and what can be assumed about validity.
- Rebinding: whether the target can change after initialization.
- Representation and arithmetic: storage cost, taking addresses, pointer arithmetic, arrays.
- Const: top-level vs low-level const for
const T*,T* const, andconst T&. - Dangling: typical situations that lead to undefined behavior (returning something temporary, invalidation after reallocation, and so on).
Part 2: Choosing Signatures
For each scenario, pick the most appropriate type from const T&, T&, T*, std::unique_ptr, std::shared_ptr, std::string_view, or std::span (or a close variant), and say what ownership and lifetime contract it expresses.
// A: Read a market update. The caller keeps ownership; it is never null.
void OnTick(/* ??? */ tick);
// B: Find a live order by id. It may not exist.
/* ??? */ FindOrder(uint64_t order_id);
// C: Take a contiguous run of price levels for vectorized aggregation.
void AggregateLevels(/* ??? */ levels);
// D: Hand a heap-allocated order request to an asynchronous lock-free queue.
void EnqueueOrder(/* ??? */ order);
Part 3: Aliasing and Optimization
Explain how aliasing rules (strict aliasing and __restrict__) apply to pointers and references. Then explain why a function taking const T& a, T& b may compile to worse code than one taking a by value.
Hints
Hint 1
Ask yourself: is a pointer an object with its own address, and is a reference one? What follows for null, rebinding, and arithmetic? Assigning to a reference never rebinds it.
Hint 2
For each scenario ask three questions: can the argument be absent, who destroys the object, and does the callee need to know the length? Those three answers pick the type.
Hint 3
When two handles of compatible type are visible, the compiler must assume a write through one can change what the other reads. Think about what that forces inside a loop, and what changes if the value is a local copy.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
A pointer is an object: it has its own storage and address, can be null, can be reassigned, and supports arithmetic. A reference is an alias: once bound, it behaves as the referent itself, so it cannot be null, rebound, or left uninitialized.
That gives a simple vocabulary for interfaces:
- A reference means "required, and I am only borrowing it."
- A raw pointer means "optional, or I need pointer mechanics", still without ownership.
- Smart pointers and views state the ownership or extent explicitly.
Part 1: Mechanics
| Aspect | T* | T& |
|---|---|---|
| Initialization | Can be uninitialized (indeterminate) or nullptr | Must be bound at declaration |
| Null | Allowed; callers must check | Not possible in well-formed code; binding to *nullptr is already UB |
| Rebinding | p = &other; points elsewhere | r = other; assigns to the referent; it never rebinds |
| Representation | A real object (8 bytes on x86-64); &p is its own address | Not an object; &r is the referent's address. Locals usually vanish after optimization, but a reference member normally costs pointer-sized storage |
| Arithmetic | p + n, p[i], p2 - p1 within one array | None. No arrays of references, no references to references, no pointers to references |
Const placement
const T* p: low-level const. The pointee is read-only throughp;pitself can be reseated.T* const p: top-level const.pis fixed; the pointee is writable.const T* const p: both.const T& r: low-level const. A reference is already effectively top-level const because it can never be rebound.T& constis ill-formed (or the const is ignored when it arrives through a typedef or template parameter).- Unlike
T&, aconst T&can bind to a temporary and extends its lifetime.
Common dangling scenarios
- Returning a reference or pointer to a local variable.
- Returning a
const T&that was bound to a temporary argument (for examplestd::max(a, 1)returning a reference to the temporary1). - Keeping
&v[i], a reference to an element, or an iterator across apush_backthat reallocates astd::vector. Forstd::unordered_map, a rehash invalidates iterators but not references or pointers to elements. - A
std::string_vieworstd::spancreated from a temporary container. - A lambda capturing by reference that runs after the enclosing scope has ended (typical in async callbacks).
- A reference member bound in a constructor to a temporary argument.
Part 2: Signatures
// A: required, borrowed, read-only
void OnTick(const MarketTick& tick);
// B: optional, borrowed
Order* FindOrder(uint64_t order_id); // nullptr means not found
// C: contiguous, borrowed, with length
void AggregateLevels(std::span<const PriceLevel> levels);
// D: ownership transfer
void EnqueueOrder(std::unique_ptr<OrderRequest> order);
A. The argument cannot be null and the caller keeps ownership, so const T& is right. A pointer would invite pointless null checks. shared_ptr would wrongly suggest shared ownership and add atomic reference-count traffic on the hot path. If MarketTick is small and trivially copyable (roughly 16 bytes or less), pass it by value instead: it goes in registers and cannot alias anything (see Part 3).
B. Absence is a normal outcome, so the return type must be able to express it. A raw Order* is the idiomatic non-owning, nullable choice, with the documented rule that it stays valid until the order leaves the book. std::optional<std::reference_wrapper<Order>> is a heavier alternative. A T& return is wrong because a miss has nothing to bind to. shared_ptr is wrong because nobody is sharing ownership.
C. std::span<const PriceLevel> bundles pointer and length, accepts a vector, std::array, or C array without copying, and states that the data is contiguous, which is what vectorized code needs. It replaces the error-prone (const T*, size_t) pair. std::string_view plays the same role for character data. Use std::span<PriceLevel> if the function must modify the levels.
D. Taking unique_ptr by value makes the caller write std::move(...), so the transfer is visible at the call site and the callee becomes the sole owner. With one producer and one consumer, shared_ptr has no justification. Inside, a lock-free queue often stores a raw pointer (release()), and the consumer re-wraps it in a unique_ptr. In very latency-sensitive systems, you would go further: preallocate orders in a pool or arena and enqueue an index or handle, which avoids heap allocation on the hot path entirely.
Part 3: Aliasing and optimization
If a function receives two pointers or references to compatible types, the compiler must assume they may refer to the same object. A store through one forces a reload through the other.
void Scale(std::span<double> out, const double& factor) {
for (double& x : out) x *= factor; // factor might be one of the x's
}
Because factor could be an element of out, each store may change it. The compiler must reload it every iteration, cannot keep it in a register, and often cannot vectorize cleanly (at best it emits a runtime overlap check plus a scalar fallback). With double factor by value, the parameter is a private local that nothing can alias, so the value stays in a register and the loop vectorizes. The same logic applies to const T& a, T& b: writes to b may change a, so reads of a cannot be cached or reordered. For small trivially copyable types, by-value usually beats const T& on both indirection and aliasing.
Strict aliasing (type-based alias analysis) lets the compiler assume that pointers or references to unrelated types do not alias: a float& and an int& are treated as distinct. The exceptions are char, unsigned char, and std::byte, which may alias anything, so stores through them force conservative code. Violating the rule through casts is UB; use std::memcpy or std::bit_cast for type punning.
__restrict__ (a GCC/Clang/MSVC extension, not standard C++) works on pointers and, in practice, references. It promises that, within the scope, the object is accessed only through that handle. This lets the compiler hoist loads and vectorize, but if the promise is broken the behavior is undefined.
Edge cases worth mentioning
- Forming a reference from a null pointer (
T& r = *p;) is UB at the moment of binding, even ifris never used. auto x = ref;makes a copy; you needauto&to keep a reference.- A
const T¶meter happily binds to a temporary, so storing it beyond the call dangles. - Pointer arithmetic outside
[begin, end]of one array is UB even if the result is never dereferenced. - Lifetime extension applies only when a prvalue is bound directly to a local
const T&orT&&.const auto& s = MakeString();is fine, but it does not carry through a function that returns a reference to its argument.
Common mistakes
- Using
shared_ptras a default "safe" pointer, which adds atomic costs and blurs ownership. - Returning
T&from a lookup that can fail. - Using
const T&for tiny types and paying for indirection and aliasing. - Treating
T&as "a pointer that cannot be null" without noticing it also cannot be rebound, so it cannot be stored in containers or reassigned. - Passing
(ptr, len)pairs wherestd::spanwould carry both safely.