Perfect Forwarding in C++

Level 5468 keystrokes

create() takes its arguments as forwarding references and passes them on with std::forward, so lvalues stay lvalues (the copy constructor runs) and rvalues stay rvalues (the move constructor runs).

C++ code

1class Widget {
2 string name;
3public:
// Chosen for lvalues: copies the string
4 Widget(const string& n) : name(n) { cout << "Copy: " << name << endl; }
// Chosen for rvalues: moves the string
5 Widget(string&& n) : name(move(n)) { cout << "Move: " << name << endl; }
6};
7
8template<typename T, typename... Args>
// Args&& in a template is a forwarding reference: binds to lvalues and rvalues
9unique_ptr<T> create(Args&&... args) {
// forward keeps each argument's value category when passing it on
10 return make_unique<T>(forward<Args>(args)...);
11}
12
13string s = "Hello";
// s is an lvalue: prints "Copy: Hello"
14auto w1 = create<Widget>(s);
// The literal becomes a temporary string, an rvalue: prints "Move: World"
15auto w2 = create<Widget>("World");
// move(s) turns s into an rvalue: prints "Move: Hello" (s should not be used afterwards)
16auto w3 = create<Widget>(move(s));
// Prints "Created 3 widgets"
17cout << "Created 3 widgets" << endl;

Output

Copy: Hello
Move: World
Move: Hello
Created 3 widgets
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 23
  • (× 12
  • )× 12
  • ;× 10
  • "× 10
  • .× 9
  • >× 7
  • :× 5
  • &× 5
  • {× 4

More C++ examples at level 5

← C++ typing practice