Avatar ·

Why is std::forward needed and what problems does it solve in C++?

I'm learning C++11 and came across std::forward. I read the documentation, but I don't fully understand why it's needed. I have a template function that takes an argument by universal reference (T&&) and passes it to another function:\n\n```cpp\ntemplate\nvoid wrapper(T&& arg) {\n target(arg); // just passing\n}\n```\n\nBut when I pass an rvalue (e.g., a temporary object), target receives it as an lvalue because arg has a name. This causes copying instead of moving. I've heard that std::forward solves this problem, but I don't understand how. Can you explain with examples: what specific problems does std::forward solve and how to use it correctly? Preferably with code to clearly see the difference. Thanks!\n<<>>\n

What is std::forward and why it's needed