Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::reference_wrapper — a copyable reference wrapper

std::reference_wrapper stores a reference without owning its target. Learn std::ref, std::cref, and the difference between modifying the referenced object and changing which object the wrapper references.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <functional>
std::reference_wrapper<T> wrapper = std::ref(object);
std::reference_wrapper<const T> readonly = std::cref(object);
wrapper.get();

std::reference_wrapper<T> from <functional> is a copyable, assignable object wrapping a reference to an object or function. A copy still refers to the same target; it does not copy that target. It is useful when a reference must be represented as an ordinary value, for example in a container. For a wrapped callable, operator() forwards the call to the target.

std::ref(x) creates std::reference_wrapper<T>, preserving the type qualifiers of x; it does not remove const. std::cref(x) creates std::reference_wrapper<const T>, providing const-qualified access to an object. A mutable data member can still be modified directly through the const reference returned by get(). Overloads accepting an existing wrapper preserve its target rather than creating a nested wrapper.

get() returns T&; an implicit conversion to T& is also available. A const std::reference_wrapper<T> does not itself add const to the referenced type. For access through a reference to const T, use std::reference_wrapper<const T>. Assignment with r = std::ref(b) changes the wrapper's target, whereas r.get() = b assigns a value to its current target.

The wrapper neither manages nor extends its target's lifetime. The target must exist whenever the reference is used; otherwise the reference dangles. The deleted overloads of std::ref and std::cref reject ordinary temporary objects as targets. The overloads that take a std::reference_wrapper, however, accept temporary wrappers. If a is an existing int object, both std::ref(std::ref(a)) and std::cref(std::ref(a)) are valid and refer to a. The wrapper has no default constructor or empty state.

This entry targets C++23. The eel.is source is an evolving draft and may contain later additions; this entry does not assume their availability.

Examples

#include <functional>
#include <iostream>

int main() {
    int a = 10;
    int b = 20;
    auto r = std::ref(a);
    auto copy = r;
    const auto readonly = std::cref(a);

    copy.get() += 5;
    r = std::ref(b);
    r.get() += 2;

    std::cout << a << ' ' << b << ' ' << readonly.get() << '\n';
}

Result

15 22 15

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources