R-Value references and std::forward

If you’ve watched STL’s excellent video about… Standard Template Library on Channel 9, you may be wondering why that forward<> template is needed.
 
I did. Wink
 
To understand why, one needs a bit more understanding of R-Value References (&&). As good as that article is, I was not satisfied with "The purpose of the std::forward function is to forward the parameters of the factory function to the constructor of the template class".
 
Why does one need that?
 
Well, it turns out that I found clarification in A Proposal to Add Move Semantics Support to the C++ Language: "Even though named rvalue references can bind to an rvalue, they are treated as lvalues when used".
 
So you won’t be surprised that the code at the bottom prints:


f(int && i) calling g(i)
        g(int &)
f(int && i) calling g(static_cast<int &&>(i))
        g(int &&)
f(int && i) calling g(static_cast<int &>(i))
        g(int &)
f(int && i) calling g(forward<int &&>(i))
        g(int &&)
f(int && i) calling g(forward<int &>(i))
        g(int &)

 
I’m not playing with the cv-qualifier here as all I want is understand the basic mechanism for now. You might also want to have a look at the forward paper.
 
I hope it helped some of you! À demain si on le veut bien.
 


void g(int &) {

   wcout << L"tg(int &)" << endl;

}

 

void g(int &&) {

   wcout << L"tg(int &&)" << endl;

}

 

void f(int && i) {

   wcout << L"f(int && i) calling g(i)" << endl;

   g(i);

   wcout << L"f(int && i) calling g(static_cast<int &&>(i))" << endl;

   g(static_cast<int &&>(i));

   wcout << L"f(int && i) calling g(static_cast<int &>(i))" << endl;

   g(static_cast<int &>(i));

   wcout << L"f(int && i) calling g(forward<int &&>(i))" << endl;

   g(forward<int &&>(i));

   wcout << L"f(int && i) calling g(forward<int &>(i))" << endl;

   g(forward<int &>(i));

}

 

int wmain() {

   f(5);

   return 0;

} 


 

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s