CarlosHD CarlosHD - 2 months ago 11
C++ Question

C++, rvalue references in function parameters

I'm trying to understand

rvalue
references. I have seen how they are used in constructors, with things like
std::move
and
std::forward
, but I still don't understand why this doesn't work:

void func(string&& str)
{
cout << str << endl;
}
int main(int argc, char* argv[])
{
string s("string");
func(s);
}


And this does:

template<typename T>
void func(T&& str)
{
cout << str << endl;
}
int main(int argc, char* argv[])
{
string s("string");
func(s);
}


Why does it work with the function template version?

Answer

Like @Peter said, the type of T is deduced as string&, and C++’s reference-collapsing rule says:

T& & ⇒ T& // from C++98
T&& & ⇒ T& // new for C++0x
T& && ⇒ T& // new for C++0x
T&& && ⇒ T&& // new for C++0x

So func’s instantiation is actually:

void func(string& str)

And it works.