Is const T& effectively the same as T&& with std::forward for rvalue argument when be passed into another function?

Is const T& effectively the same as T&& with std::forward for rvalue argument when be passed into another function?
typescript
Ethan Jackson

Say I have a const T& version:

<typename T> void yetAnotherFunc( const T &input ) { // do something... } <typename T> void myFunc( const T &input ) { yetAnotherFunc( input ); } int main() { myFunc( someT() ); // pass in a rvalue return 0; }

Is it effectively same as the T&& with std::forward below in terms of no copy is involved? what differences are there?

<typename T> void yetAnotherFunc( T &&input ) { // do something... } <typename T> void myFunc( T &&input ) { yetAnotherFunc( std::forward<T>( input ) ); } int main() { myFunc( someT() ); // pass in a rvalue return 0; }

Answer

In the first example yetAnotherFunc receives a reference to a const T, which it can not modify without a const_cast.

In the second example yetAnotherFunc receives a reference to a non-const T, which it could modify. And by convention, the second yetAnotherFunc could modify the T without fear of having any other part of the program notice since the caller declared the argument an rvalue or "temporary value".

In either example, no copies or moves are made. Things are just being passed around by reference. The only difference is the const qualification, and whether yetAnotherFunc sees an lvalue or an rvalue.

If yetAnotherFunc sees an lvalue, then by convention, if yetAnotherFunc modifies the value, then it has to assume that other parts of the program can see that modification.

If yetAnotherFunc sees an rvalue, then by convention, if yetAnotherFunc modifies the value, then it can assume that other parts of the program can not see that modification.

For more help on this issue, see type_name to print out the type of input in each function.

Related Articles