﻿# The std::forward function

The _std::forward_ function as the [_std::move_ function](https://pvs-studio.com/en/blog/terms/6518/) aims at implementing [move semantics](https://pvs-studio.com/en/blog/terms/6514/) in C\+\+\. The function takes a [forwarding reference](https://pvs-studio.com/en/blog/terms/6517/)\. According to the _T_ template parameter, std::forward identifies whether an lvalue or an rvalue reference has been passed to it and returns a corresponding kind of reference\. _std::forward_ helps to implement perfect forwarding\. This mechanism implies that objects passed to the function as lvalue expressions should be copied, and objects passed to the function as rvalue expressions should be moved\.

If you assign an rvalue reference to some _ref _variable, then _ref_ is a named entity\. Therefore, its category is lvalue, despite the fact that _ref_ is an rvalue reference\. Therefore, for _ref_ copy semantics is used instead of move semantics\.

The _std::forward_ function solves this problem\. Let's consider the following example: 

```cpp
template <typename T>
void foo(T &&arg)
{
  std::vector<int> var = arg;
  ....
}

std::vector<int> vect(1'000'000, 1);
foo(std::move(vect));
```

That's what happens in the code fragment:

* The _std::move_ function is called\. It returns an rvalue reference to _vect_\.
* This reference is passed via a forwarding link to the instance of the _foo_ function as the _arg_ argument\. _arg_ is an lvalue object of the rvalue reference type\.
* The _var_ variable is initialized\. It calls the copy constructor\. _vector vect_ is copied element\-by\-element to the _var_ variable\.

Now let's use _std::forward_:

```cpp
template <typename T>
void foo(T &&arg)
{
  std::vector<int> var = std::forward<T>(arg);
  ....
}

std::vector<int> vect(1'000'000, 1);
foo(std::move(vect));
```

Here's what happens:

* The _std::move_ function is called\. It returns an rvalue reference to _vect_\.
* This reference is passed via a forwarding link to the instance of the _foo_ function as the _arg_ argument\. _arg_ is an lvalue object of the rvalue reference type\.
* The _std::forward_ function is called\. It returns an [xvalue object](https://pvs-studio.com/en/blog/terms/6517/) with the rvalue reference type\.
* The _var_ variable is initialized\. It calls the move constructor\. _vector vect_ is moved to the _var_ variable\.