KatInterview

Pointers vs References in C++: Semantics and API Design

Data Structure DesignModel answer
MediumModel answerData Structure Designcpppointersreferences

Last 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:

  1. Initialization and nullability: what must happen at declaration, and what can be assumed about validity.
  2. Rebinding: whether the target can change after initialization.
  3. Representation and arithmetic: storage cost, taking addresses, pointer arithmetic, arrays.
  4. Const: top-level vs low-level const for const T*, T* const, and const T&.
  5. 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.