C++ 11 feature: Forwarding References

Forwarding Reference is a new feature in C++11.

They are also called as Universal References. It means, it will binds to both lvalues and rvalues. We will see in example further below.

Forwarding reference uses the syntax “T&&” or “auto&&”.

What is the difference between rvalue reference and forward reference ?

rvalue reference looks like “int &&”.

Forward Reference looks like “auto&&” or “T&&”.

So if we use template paramter type or “auto”, then it is a forward reference.

Let us understand both with an example:

We have taken 2 functions, “multiply()” “add()“.

multiply( int&& x ) properties:

1. It is taking a rvalue reference to a non-const as input.

2. x argument has to be always rvalue.

3. x argument is capturing temp values.

template <typename T>

add( T&& x ) properties:

1. “add()” takes lvalue or rvalue reference to const, volatile or both.

2. T argument can be of any type.

3. T argument is forwarding the arguments.

Examples:

int var = 20 // var is alvalue of type int.

multiply(10); // works as multiply accepts rvalue type.

multiply(var); // error. as multiply (int&) is not ok. Because var should be of rvalue type.

add(10); // this is ok

add (var); // this is ok, as var can be of rvalur or lvalue

.

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *