C++ perfect forwarding

Poby’s Home
1 min readFeb 25, 2021

--

When you want to forward arguments to template function/method without changing the value category

Perfect forwarding

refers to a template function or method which passes arguments

  • 1. to another function or method
  • 2. preserving the const qualifier and lvalue/rvalue category

std::move( ) vs std::forward( )

std::move

  • force the value category as a rvalue. It is basically a casting to rvalue

std::forward

  • pass in an original reference type. If what is passed is a rvalue, then convert it as a rvalue category. If what is passed to is a lvalue, then pass as a lvalue category.
#include <iostream>
#include <vector>
using namespace std;
class Foo
{
public:
Foo() = default;
Foo(int a, bool b, const vector<int> &v)
: mA(a), mB(b), mV(v) {}
Foo(int a, bool b, vector<int> &&v)
: mA(a), mB(b), mV(move(v)) {}
virtual ~Foo() {}
private:
int mA;
bool mB;
vector<int> mV;
};
class Bar
{
public:
template <typename... Args>
void addFoo(Args &&...args)
{
mFoo.emplace_back(forward<Args>(args)...);
}
private:
vector<Foo> mFoo;
};
static void printVector(vector<int> const &v)
{
for (auto e : v)
{
cout << e << endl;
}
}
int main()
{
Bar b;
vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2 = {6, 7, 8, 9};
b.addFoo(1, true, v1); // Foo will receive it as lvalue ref
b.addFoo(2, false, move(v2)); // Foo will receive it as rvalue ref
cout << "V1 ------" << endl;
printVector(v1);
cout << "V2 ------" << endl;
printVector(v2);
return 0;
}

result

~/ProgramingPractice/C++$ ./a.out 
V1 ------
1
2
3
4
5
V2 ------

--

--

No responses yet