Why does std::thread t(encode, id, stats) fail to compile when encode takes SegmentStats&, and what does std::ref change?
answer
- arguments are stored before the call
- decayed copies owned by the thread
- the stored copy is an rvalue
- reference_wrapper converts back to T&
basics
~20 sstd::thread copies or moves every argument into storage the new thread owns and passes those copies as rvalues, which a SegmentStats& parameter cannot bind. std::ref(stats) passes a copyable reference_wrapper that converts back to a reference to the original.
solid answer
~40 sThe standard says the new thread runs `invoke(auto(std::forward<F>(f)), auto(std::forward<Args>(args))...)`, with those values materialized in the constructing thread; earlier standards spelled the same thing *decay-copy*. So `stats` is copied into thread-owned storage and handed to `encode` as an rvalue. The constructor *mandates* `is_invocable_v<decay_t<F>, decay_t<Args>...>`, and an rvalue cannot bind to a non-const `SegmentStats&`, so the program is ill-formed. `std::ref(stats)` stores a `std::reference_wrapper<SegmentStats>`, which is cheap to copy and converts implicitly to `SegmentStats&`, so `encode` works on the caller's object. That shifts two duties to you: the object must outlive the thread, and concurrent access must be synchronized. The silent version is worse: with a by-value or `const&` parameter it compiles, and the thread reads a snapshot.
code
cpp · 11 lines#include <thread>
struct SegmentStats { int frames = 0; };
void encode(int id, SegmentStats& stats) { stats.frames += 240 + id; }
int main() {
SegmentStats stats;
std::thread t(encode, 1, stats); // stats would be copied: rejected
t.join();
}go deeper
Remember that std::thread copies its arguments and that std::ref is how a reference parameter reaches the caller's object.
Explain decay-copy, why the stored copy is an rvalue, and which parameter types compile silently against a copy.
Spot the lifetime bug behind std::ref, pointers and reference captures, including the char buffer converted inside the new thread.
Set a review rule for thread entry points: owning parameters by default, references only with a visible join in the same scope.
## What the std::thread constructor stores `std::thread t(f, a, b)` does not call `f(a, b)`. Before the constructor returns, it makes **decayed copies** of `f` and of every argument, in the constructing thread, and hands them to the new thread. The C++23 wording writes this as `invoke(auto(std::forward<F>(f)), auto(std::forward<Args>(args))...)`; C++11 to C++20 called the same operation *decay-copy*. Three consequences follow: - Lvalue arguments are **copied**, rvalue arguments are **moved**. - Arrays and functions **decay** to pointers; references and cv-qualifiers are stripped. - The stored copies are passed to `f` as **rvalues**. The constructor *mandates* that `decay_t<F>` is invocable with `decay_t<Args>...`, so a mismatch is a compile error, not a runtime surprise. ## Why a non-const reference parameter is rejected Take a transcoder worker `void encode(int id, SegmentStats& stats)` and the call `std::thread t(encode, 1, stats);`. The stored copy of `stats` is an rvalue `SegmentStats`, and a non-const lvalue reference cannot bind to an rvalue. libc++ reports it as a failed `static_assert` on `__is_invocable_v` (see the diagnostic below); libstdc++ reports its own error. The compiler is protecting you: the thread could only ever have updated a copy that nobody reads. ## std::ref and std::cref `std::ref(stats)` returns a `std::reference_wrapper<SegmentStats>`. Copying the wrapper copies a pointer, and the wrapper converts implicitly to `SegmentStats&`, so `encode` now updates the caller's object. `std::cref` does the same for `const T&`. With a wrapper you take on two obligations: 1. **Lifetime**: the referenced object must outlive every use by the thread, so join before it goes out of scope. 2. **Synchronization**: if any other thread touches the object while the worker runs, that is a data race, which is undefined behaviour unless a mutex or atomics order the accesses. ## Why the copies happen in the calling thread The standard requires the decayed copies to be **materialized in the constructing thread**, and its note draws the consequence: an exception thrown while copying `f` or an argument is thrown from the `std::thread` constructor, in the caller, not inside the new thread. The completion of the constructor also **synchronizes with** the start of the copied function, so everything the caller wrote before constructing the thread, including the copied arguments, is visible to the worker without further locking. Only what happens *after* the constructor returns, such as the caller changing an object it passed with `std::ref`, needs synchronization. ## The cases that compile and still surprise | Parameter of `encode` | Argument | Result | |---|---|---| | `SegmentStats&` | `stats` | ill-formed: rvalue cannot bind | | `SegmentStats&` | `std::ref(stats)` | works on the caller's object | | `const SegmentStats&` | `stats` | compiles; binds to the thread's **copy** | | `SegmentStats` | `stats` | compiles; the copy's changes are lost | | `const std::string&` | `char buf[64]` | stores a `char*`; the `std::string` is built **in the new thread** | | `std::unique_ptr<Frame>` | `std::move(frame)` | moves the pointer into the thread | The `char` buffer row is a classic bug. Decay turns the array into a pointer, and the conversion to `std::string` happens when the new thread invokes the function. If the caller then returns, or the thread was detached, the conversion may read a dead buffer: undefined behaviour. Pass `std::string(buf)` so the copy happens before the constructor returns. ## Member functions and lambdas For `std::thread t(&Encoder::run, &enc, id)` the stored copy is the **pointer** `&enc`, so `enc` must outlive the thread exactly as with `std::ref`. A lambda that captures by reference, `[&] { encode(id, stats); }`, has the same lifetime obligation without the visible `std::ref` that would warn a reviewer. Capturing by value copies at the point the lambda is created, which is usually what a detached task needs. ## Checklist - Read the parameter list before writing the `std::thread` call. - Use `std::ref` or `std::cref` only when the thread must see the caller's object, and join before it dies. - Convert pointers to buffers into owning values before handing them to a thread. - Move move-only arguments in with `std::move`.
- What happens if encode takes its stats by value or by const reference instead?Both compile. The thread works on the copy the constructor made in the calling thread, so a by-value parameter's changes are lost and a `const&` parameter sees a snapshot taken at construction, not later updates. Nothing warns you, which makes it worse than the compile error.
- Why is passing a char buffer to a thread whose function takes const std::string& dangerous?The array decays to a `char*`, and only that pointer is copied. The `std::string` is constructed later, inside the new thread, when the function is invoked. If the caller has returned or the thread was detached, that construction reads a destroyed buffer, which is undefined behaviour. Pass `std::string(buf)` so the copy happens before the constructor returns.
- How do you hand a std::unique_ptr<Frame> to a worker thread?Move it in: `std::thread t(process, std::move(frame));` with a parameter of type `std::unique_ptr<Frame>` or `std::unique_ptr<Frame>&&`. Passing the lvalue fails because the constructor mandates that each decayed argument is constructible from what you passed, and `unique_ptr` is not copyable.
- std::thread passes its arguments to the function by reference, like a direct call.
- A const SegmentStats& parameter lets the thread see the caller's later changes.
- std::ref makes the shared object safe to use from both threads.
- A char array argument becomes a std::string before the constructor returns.
- Capturing everything by reference in a lambda avoids lifetime problems.