Why can't a C++ std::vector hold Point& elements, and what does std::reference_wrapper change?
answer
- elements must be objects
- allocator of a reference type
- rebinding copy assignment
- std::ref and std::cref
basics
~20 sContainer 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&.
solid answer
~40 sStandard containers allocate, construct, assign and destroy their elements, and the allocator requirements are stated for cv-unqualified **object** types; `std::vector<Point&>` fails inside `std::allocator` because it would declare a pointer to a reference. `std::reference_wrapper<Point>` is a trivially copyable class that stores a reference: copy-constructible, copy-assignable (assignment **rebinds**), implicitly convertible to `Point&`, with `get()` for member access. So `std::vector<std::reference_wrapper<Point>>` can be sorted to give an ordered view over points owned elsewhere without copying them. `std::ref(x)` and `std::cref(x)` build wrappers, and `std::bind` and `std::thread`, which copy their arguments, pass a real reference only when given one. `std::ref` on a temporary is deleted, which stops the most obvious dangling wrapper.
code
cpp · 24 lines#include <algorithm>
#include <cstdio>
#include <functional>
#include <vector>
struct Point { double x, y; };
void nudge(Point& p, double dx) { p.x += dx; }
int main() {
Point a{3, 0}, b{1, 0}, c{2, 0};
// A sorted view over points owned elsewhere: no copies of the Points.
std::vector<std::reference_wrapper<Point>> byX{a, b, c};
std::sort(byX.begin(), byX.end(),
[](const Point& l, const Point& r) { return l.x < r.x; });
byX.front().get().x = 0.5; // writes through to b
// std::bind copies its arguments unless you pass std::ref.
auto copyNudge = std::bind(nudge, c, 10.0); // binds a copy of c
auto refNudge = std::bind(nudge, std::ref(c), 10.0); // binds c itself
copyNudge();
refNudge();
std::printf("b.x=%.1f c.x=%.1f first=%.1f\n", b.x, c.x, byX[0].get().x);
}go deeper
Recall that containers cannot store references, that std::reference_wrapper is the copyable stand-in, and that std::ref and std::cref create one.
Explain why elements must be object types, how the wrapper's assignment rebinds, and why get() is needed for member access but not for passing to a T& parameter.
Use wrapper vectors for multiple orderings of non-copyable objects, use std::ref with copying interfaces such as std::bind, and keep the referents alive longer than the wrappers.
Decide when a codebase should model non-owning collections with reference_wrapper, raw pointers or indices, weighing never-null guarantees against simplicity and lifetime risk.
## Why containers refuse references A container element is an object that the container creates, copies, assigns and destroys through its allocator. The library's allocator requirements are written for any **cv-unqualified object type**, and a reference is not an object type. Concretely, `std::allocator<Point&>` would need `Point&*` - a pointer to a reference - and the language says "there shall be no references to references, no arrays of references, and no pointers to references". Clang with libc++ stops inside `allocator.h` with "'allocate' declared as a pointer to a reference of type 'Point &'". Even if storage were solved, assignment would be meaningless: a reference cannot be reseated, so `v[0] = v[1]` could only copy one `Point` into another, and sorting would scramble the original points instead of the container. ## What std::reference_wrapper is `std::reference_wrapper<T>`, in `<functional>`, is a class template that holds a reference as an object. The standard describes it as a copy-constructible and copy-assignable wrapper around a reference, and requires it to be **trivially copyable**. Its interface is small: - `reference_wrapper(T&)` - construct from an lvalue; construction from an rvalue is rejected; - `operator T&() const` - implicit conversion, so it can be passed where a `T&` is expected; - `T& get() const` - explicit access, needed for member access (`w.get().x`), since `.` cannot trigger a conversion; - `operator()` - if `T` is callable, calls it through `std::invoke` rules; - `operator=` - **rebinds** the wrapper to the other wrapper's referent. Class template argument deduction works too: `std::reference_wrapper r{p};` deduces `reference_wrapper<Point>`. ## Use 1: views over existing objects ```cpp std::vector<std::reference_wrapper<Point>> byX{a, b, c}; std::sort(byX.begin(), byX.end(), [](const Point& l, const Point& r) { return l.x < r.x; }); byX.front().get().x = 0.5; // writes into the original Point ``` The comparator takes `const Point&`, and the wrappers convert implicitly. Sorting shuffles wrappers - cheap trivially copyable objects - while `a`, `b` and `c` stay where they are. This is how you keep several orderings of objects you do not want to copy or that are not copyable. ## Use 2: passing references through copying interfaces Some library facilities **decay-copy** their arguments before use: `std::bind`, `std::thread`, `std::make_pair` and `std::make_tuple` among them. Passing a variable gives the callee a copy: 1. `std::bind(nudge, c, 10.0)` stores a copy of `c`; calling it nudges the copy. 2. `std::bind(nudge, std::ref(c), 10.0)` stores a `reference_wrapper`; when the bound call runs, the wrapper unwraps to `Point&` and `c` itself changes. 3. `std::make_pair(std::ref(x), 1)` produces a `std::pair<int&, int>`, because the make functions unwrap reference wrappers into reference members. Thread-argument copying in detail is covered with threads; the mechanism is the same wrapper. ## Safety features and limits - `std::ref(const T&&)` and `std::cref(const T&&)` are declared **deleted**, so `std::ref(Point{1, 2})` fails with "call to deleted function 'ref'". This blocks the most obvious dangling wrapper, not all of them: a wrapper still dangles if its lvalue referent dies first. - A wrapper is never null - it is always constructed from a reference - so it is a better optional-free member than a raw pointer when "always refers to something" is the contract. - Comparisons: before C++26, `reference_wrapper` had no comparison operators of its own; comparisons worked only when the implicit conversion found a non-template operator, so two `reference_wrapper<std::string>` objects could not be compared with `==` in C++20. C++26 adds `operator==` and `operator<=>` to the wrapper itself; Apple clang with libc++ accepts that comparison under `-std=c++2c` and rejects it under `-std=c++20`. ## Cost and generic code The standard requires only that the wrapper be trivially copyable; libc++ implements it as a single stored pointer, so with Apple clang on arm64 `sizeof(std::reference_wrapper<double>)` is 8, the same as a `double*`. Sorting a vector of wrappers therefore moves pointer-sized objects, not the referents. Generic code sometimes has to undo the wrapping. C++20's `std::unwrap_reference_t<T>` maps `reference_wrapper<U>` to `U&` and leaves other types alone, and `std::unwrap_ref_decay_t<T>` decays first - the rule `std::make_pair` and `std::make_tuple` apply when they turn a wrapper into a reference member. A factory of your own that stores its arguments can use the same trait to honour `std::ref` from callers. ## When to choose it | Need | Choice | |---|---| | a container of non-owning, never-null references | `std::vector<std::reference_wrapper<T>>` | | a container that also allows "no element" | `std::vector<T*>` | | shared ownership | a smart pointer, covered with the ownership material | | pass by reference through `std::bind` or `std::thread` | `std::ref` / `std::cref` |
- Why does accessing a member need w.get().x instead of w.x?Member access with `.` never looks for conversion functions; it looks for a member named `x` in `reference_wrapper` itself and finds none. Passing `w` to a function taking `Point&` works because overload resolution does consider the implicit `operator T&()`. `get()` makes the conversion explicit, and it is also what you use in comparisons and output.
- What does C++26 change about comparing std::reference_wrapper objects?Before C++26, `reference_wrapper` had no comparison operators, so `r1 == r2` compiled only if converting to `T&` found a non-template `operator==`; for `std::string`, whose comparisons are templates, it failed. C++26 adds `operator==` and `operator<=>` taking wrappers and `const T&`, so wrappers of any comparable type compare directly. Apple clang with libc++ accepts it under `-std=c++2c`.
- std::vector<Point&> works but is discouraged
- Assigning one reference_wrapper to another copies the referred Point
- std::ref(x) copies x into a wrapper that then behaves like a reference
- std::bind passes its arguments by reference automatically
- std::ref can wrap a temporary to keep it alive
Assumes C++23; the comparison operators on std::reference_wrapper itself are new in C++26 (checked with Apple clang -std=c++2c).