Reputation: 9
#include <iostream>
void bar(std::string& s) { std::cout << "ref" << std::endl;}
void bar(const std::string& s) { std::cout << "const ref" << std::endl;}
void bar(std::string&& s) { std::cout << "rvalue ref" << std::endl;}
int main (int argc, char *argv[]) {
const std::string text{"text"};
bar(text);
bar(std::string{"text"});
bar("text");
std::string text1{"text"};
bar(text1);
bar(std::move(text));
return 0;
}
I expected rvalue ref to be printed for the last function call, not const ref. Why is const ref printed instead of rvalue ref? I thought that std::move takes the text variable and adds && to it and turns it into an rvalue ref, but it obviously doesn't work that way. Since rvalue can be bound to both rvalue ref and const ref, which one has priority? Can someone help me?
Upvotes: 0
Views: 92
Reputation: 63471
Casting a const value as a rvalue reference does not magically discard the const-qualifier. So it's essentially const std::string&&
. The closest match for that type in the functions you provided is const std::string&
.
Upvotes: 2