Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 rvalue reference vs const reference

Tags:

c++

c++11

This may be obvious but I think it is something difficult to me. Given this:

void test(std::string&&) { }

std::string x{"test"};
test(std::move(x)); // ok

This code calls test() with a rvalue reference as parameter so the program compiles as I expect.

Now look at this:

void other_test(const std::string&) { }

std::string x{"test"};
other_test(std::move(x)); // ok???

And here I'm tilted. Why does this version compile? The std::move returns a && type; why then I don't get an error in the second method where I use const&?


I know that

int&& s = 5;
const int& s = 5;

is valid because in both cases I provide something that has not an lvalue, it has no addresses. Are && and const& equivalent? If no, are there differences?

like image 386
Emma Rossignoli Avatar asked Aug 30 '18 20:08

Emma Rossignoli


1 Answers

When you call std::move(x), an rvalue reference to the underlying data, test, will be returned. You are allowed to pass rvalue references as const (and const only!) reference parameters because an rvalue reference is implicitly convertible to a const reference. They are arguably the same thing from the function's point of view (a read only parameter). If you removed the const-qualifier of your parameter, this code would not compile:

void other_test(std::string&) { }
std::string x{"test"};
other_test(std::move(x)); //not okay because
//the function can potentially modify the parameter.

See Bo Qian's youtube video on rvalue vs lvalue.

like image 196
N. Prone Avatar answered Sep 20 '22 04:09

N. Prone