What is perfect forwarding in C++ (std::forward)?

A function template can take any argument and pass it on without extra copies. T&& in a template is a forwarding reference, and std::forward<T>(x) keeps the original category.

#include <iostream>
#include <string>
#include <utility>

void take(const std::string&) { std::cout << "got an lvalue (copy needed)\n"; }
void take(std::string&&)      { std::cout << "got an rvalue (can move)\n"; }

template <typename T>
void forward_it(T&& x) {
    take(std::forward<T>(x));
}

int main() {
    std::string s = "text";
    forward_it(s);                      // lvalue
    forward_it(std::string("temp"));    // rvalue
}
Output

got an lvalue (copy needed)
got an rvalue (can move)

This is how std::make_unique, emplace_back and std::thread pass your arguments to constructors.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.