Skip to content

Reference Wrapper

DryPerspective edited this page Oct 8, 2023 · 2 revisions

A reference_wrapper is a trivially copyable wrapper around a reference, allowing references to be passed "by value" and used in containers and other facilities which ordinarily cannot accept references. A reference_wrapper may be cast back to a reference as needed, either implicitly or through its get() member function. Assignment to a reference wrapper rebinds the held reference.

A reference_wrapper does not own and will not extend the lifetime of its referred-to object. Undefined behaviour will occur if a reference_wrapper which refers to a destroyed object is accessed.

Invoking a reference_wrapper through operator() is not supported.

Features

reference_wrapper A trivially copyable wrapper around a reference
ref
cref
Helper functions to create a reference_wrapper<T> and reference_wrapper<const T>

Sample code

#include <vector>
#include "cpp98/reference_wrapper.h"

int main(){
    int x = 1;
    int y = 2;
    int z = 3;

    //std::vector<int&> vec; <- compiler error, can't store or copy references
    std::vector<dp::reference_wrapper<int> > vec;
    vec.push_back(dp::ref(x));
    vec.push_back(dp::ref(y));
    vec.push_back(dp::ref(z));
    for(std::size_t i = 0; i < vec.size(); ++i){
        vec[i] *= 2;
    }
    Print(x); //Prints 2
    Print(y); //Prints 4
    Print(z); //Prints 6
}

Clone this wiki locally