PERFECT FORWARDING

Perfect forwarding is an important concept because it can significantly improve performance with large objects that take significant time to copy or create. Perfect forwarding is only relevant in the context of a class or function template. At first sight it sounds a little complicated but once you grasp the idea, it is quite simple. So what is perfect forwarding?

Suppose you have a function, fun1(), that is parameterized by a class type, T. This could be defined by a function template or be within a class template. Suppose also that fun1() is defined with an rvalue reference parameter of type T&&. You know from Chapter 6 that fun1() can be called with an argument that is an lvalue, an lvalue reference, or an rvalue. An lvalue or an lvalue reference argument results in the fun1() template instance having an lvalue reference parameter. Otherwise, it has an rvalue reference parameter.

Suppose further that fun1() calls another function, fun2(), that comes in two versions, one that has an lvalue reference parameter and another with an rvalue reference parameter. fun1() passes the argument it receives as the argument to fun2(). Ideally, when the argument received by fun1() is an rvalue reference, you want it to call the version of fun2() that has an rvalue reference parameter so there is no moving or copying of the original argument. When fun1() is instantiated and called with an lvalue or an lvalue reference argument, you want it to call the version of fun2() that ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.