std::forward

From Cppreference

Jump to: navigation, search
Defined in header <utility>

template< class T >
T&& forward( typename std::remove_reference<T>::type& t );
(1) (C++11 feature)
template< class T >
T&& forward( typename std::remove_reference<T>::type&& t );
(2) (C++11 feature)

Implements perfect forwarding, such as in a function template, when t is a function parameter which needs to be passed as an argument to another function as-is: if t is an rvalue, an rvalue is forwarded, if t is an lvalue, an lvalue is forwarded.

Contents

[edit] Parameters

t - the object to be forwarded

[edit] Return value

static_cast<T&&>(t)

[edit] Exceptions

noexcept specification:  
noexcept

  (C++11 feature)

[edit] Example

This example demonstrates perfect forwarding of the parameter of the function make_unique() to the argument of the constructor of class T

#include <iostream>
#include <memory>
#include <utility>
 
struct A {
    A(int&& n) { std::cout << "rvalue overload, n=" << n << "\n"; }
    A(int& n)  { std::cout << "lvalue overload, n=" << n << "\n"; }
};
 
template<typename T>
std::unique_ptr<T> make_unique(T&& t) 
{
    return std::unique_ptr<T>(new T(std::forward<T>(t)));
}
 
int main()
{
    std::unique_ptr<A> p1 = make_unique<A>(2); // rvalue
    int i = 1;
    std::unique_ptr<A> p2 = make_unique<A>(i); // lvalue
}

Output:

rvalue overload, n=2
lvalue overload, n=1

[edit] Complexity

Constant

[edit] See also

move (C++11)
obtains an rvalue reference
(function template)
move_if_noexcept (C++11)
obtains an rvalue reference if the move constructor does not throw
(function template)