In C++, when do you write std::forward<T>(x) and when std::move(x) to pass an argument on?
answer
- one cast is unconditional
- the other depends on T
- forwarding references only
- objects you own and are done with
basics
~20 sstd::move(x) always yields an rvalue: use it on objects you own and no longer need. std::forward<T>(x) yields an rvalue only if the caller passed one: use it only on a forwarding reference T&& x in a template.
solid answer
~40 sBoth are casts in `<utility>`; neither moves anything. `std::move(x)` is unconditional: the result is always an xvalue, which tells the receiver it may steal from `x`. That is right for a local, a by-value parameter, or a `std::string&&` parameter of a concrete type - objects the function owns. `std::forward<T>(x)` returns `static_cast<T&&>(x)`, and in `template<class T> void wrap(T&& x)` the deduced `T` remembers whether the caller passed an lvalue (`T` is `U&`, so the result is an lvalue) or an rvalue (`T` is `U`, so the result is an xvalue). Using `std::move` in the wrapper would steal from a caller's named object; passing plain `x` would always copy. And `std::forward` without the explicit `<T>` does not compile.
code
cpp · 29 lines#include <iostream>
#include <memory>
#include <string>
#include <utility>
struct Sink {
std::string name;
explicit Sink(const std::string& n) : name(n) { std::cout << " copied name\n"; }
explicit Sink(std::string&& n) : name(std::move(n)) { std::cout << " moved name\n"; }
};
template <class T, class A> std::unique_ptr<T> by_forward(A&& a) {
return std::make_unique<T>(std::forward<A>(a));
}
template <class T, class A> std::unique_ptr<T> by_move(A&& a) {
return std::make_unique<T>(std::move(a));
}
template <class T, class A> std::unique_ptr<T> by_name(A&& a) {
return std::make_unique<T>(a);
}
int main() {
std::string path = "core.log";
std::cout << "forward, lvalue:\n"; by_forward<Sink>(path);
std::cout << "forward, rvalue:\n"; by_forward<Sink>(std::string("net.log"));
std::cout << "name, rvalue:\n"; by_name<Sink>(std::string("io.log"));
std::cout << "move, lvalue:\n"; by_move<Sink>(path);
std::cout << "caller's path size now: " << path.size() << '\n';
}go deeper
Remember the split: std::move for objects you own and are done with, std::forward<T> for T&& parameters of a function template.
Explain that both are casts and that std::forward's result depends on T, which deduction set from the caller's argument.
Name the failure each misuse causes - a caller's object stolen, a temporary copied, a double forward - and spot them in review.
Treat forwarding wrappers as API surface: decide where a team really needs them, because each one adds deduction edge cases to every caller.
## Two casts, two jobs `std::move` and `std::forward` both live in `<utility>`, both are `constexpr` and `noexcept`, and both are nothing more than a `static_cast`. They differ in **when** the result is an rvalue: | | `std::move(x)` | `std::forward<T>(x)` | |---|---|---| | Result | always an xvalue | an lvalue if `T` is an lvalue reference type, otherwise an xvalue | | Standard's Returns clause | `static_cast<remove_reference_t<T>&&>(t)` | `static_cast<T&&>(t)` | | Template argument | deduced | must be written explicitly | | Use it on | objects the function owns: locals, by-value parameters, concrete `T&&` parameters | a forwarding reference `T&& x` (or `auto&& x`) | | Message to the receiver | "you may steal this" | "treat this the way my caller handed it to me" | Neither cast touches the object. Whether anything is moved is decided afterwards, by overload resolution in the function that receives the cast expression: an xvalue lets a `T&&` overload such as a move constructor win, and an lvalue rules out every `T&&` overload. So the choice between the two casts is really a choice about which overloads the receiver may pick. ## Why a wrapper needs the conditional one A **forwarding wrapper** accepts anything and hands it on, for example a factory that builds a logger from whatever constructor arguments it receives: ```cpp template <class T, class... Args> std::unique_ptr<T> make_logger(Args&&... args) { return std::make_unique<T>(std::forward<Args>(args)...); } ``` The wrapper has no idea whether the caller is done with each argument. If the caller wrote `make_logger<FileSink>(path, 2)` with a named `std::string path`, the caller still owns `path` and expects it intact. If the caller wrote `make_logger<FileSink>(std::string("net.log"), 2)`, the string is a temporary and moving it is free. Only the deduced type `Args` knows which case applies, and `std::forward<Args>` reads it. ## What goes wrong with each mistake - **`std::move` in a forwarding wrapper.** The caller's named `path` is cast to an xvalue and moved from. The caller's string is left valid but unspecified - libc++ leaves it empty - without the caller ever writing `std::move`. - **Passing the name with no cast.** Inside the wrapper every parameter has a name, so each one is an lvalue. A temporary the caller handed in is copied instead of moved, which defeats the purpose of the wrapper. - **`std::forward` without `<T>`.** Its parameter type is `remove_reference_t<T>&`, from which `T` cannot be deduced; Clang reports "candidate template ignored: couldn't infer template argument". - **Forwarding the same argument twice.** The first `std::forward` may move from it; a second use then sees a moved-from object. Forward each argument once, at its last use. - **`std::forward` on a non-template `std::string&&` parameter.** It works if written as `std::forward<std::string>(s)`, but it hides the intent; `std::move` says the same thing plainly. ## A rule of thumb that holds 1. Is the parameter declared `T&&` (or `Args&&...`, or `auto&&`) with `T` deduced right there? Then it is a forwarding reference: use `std::forward<T>`. 2. Otherwise, does the function own the object and not need it again? Then use `std::move`. 3. Otherwise, pass the name and let it be copied or bound to a `const` reference. The mechanism that lets `T` carry the caller's category - deduction of `U&` for lvalues and reference collapsing - is worth knowing in depth, but the decision above needs only the three questions. ## Where each cast appears in real code - **Constructors taking a by-value parameter** - `Logger(std::string name) : name_(std::move(name)) {}` - use `std::move`: the parameter is the constructor's own copy. - **Sink setters with a concrete `T&&`** - `void set_path(std::string&& p) { path_ = std::move(p); }` - use `std::move`. - **Moving out of a container slot you are about to drop** - `auto job = std::move(queue.back()); queue.pop_back();` - use `std::move`. - **Factories and emplace-style wrappers** - `std::make_unique<T>(std::forward<Args>(args)...)` - use `std::forward`. - **Generic invokers** - `std::invoke(std::forward<F>(f), std::forward<Args>(args)...)` - forward the callable too, because its call operator may be ref-qualified. - **Generic lambdas** - `[](auto&& x) { sink(std::forward<decltype(x)>(x)); }` - there is no named `T`, so `decltype(x)` stands in for it. When a reviewer sees `std::move` applied to a parameter whose type is a deduced `T&&`, or `std::forward` applied to anything else, one of the two is almost always wrong.
- Why does std::forward have a second overload taking remove_reference_t<T>&&?It lets you forward an rvalue expression, such as a member of a forwarded object or the result of a function call. Its specification adds a Mandates clause: `is_lvalue_reference_v<T>` must be false, so a call that would turn an rvalue into an lvalue reference is rejected at compile time - libc++ spells it as a `static_assert` with the message "cannot forward an rvalue as an lvalue".
- In a lambda written as [](auto&& x) { sink(...); }, what goes in place of the dots to forward x?`std::forward<decltype(x)>(x)`. A generic lambda has no named template parameter, but `decltype(x)` is `U&` for an lvalue argument and `U&&` for an rvalue one. Collapsing turns `U&&` plus `&&` into `U&&`, so the cast yields an xvalue for rvalues and an lvalue for lvalues - the same result as `std::forward<T>` in an ordinary template.
- std::forward and std::move are interchangeable inside a template.
- std::forward moves the argument when the callee prefers it.
- Passing a forwarding reference by name keeps its value category.
- std::forward can deduce its template argument from the expression.
- Using std::move in a forwarding wrapper is harmless because callers pass temporaries.