I am a bit confused when casting a reference to another reference. I am thinking of this in two ways and I don't know which way is correct. Here are the two ideas:
When casting a reference to a reference, reference collapsing happens. This means that whenever you cast a reference to another reference, it collapses to a reference(either LValue or RValue). For example, I use
static_cast
to cast a LValue reference to a RValue reference, it collapses down to a LValue reference due to reference collapsing rules.When casting a reference to a reference, reference collapsing does not happen and just turns the reference to the other reference. This means that if I was to cast a reference to another reference, there is no collapsing rules and it just turns the reference to that specific reference(either LValue or RValue). For example, I was to use
static_cast
to cast a LValue reference to a RValue reference, it would become a RValue reference because it just turns the LValue reference to a RValue reference without reference collapsing.
These explanations are probably pretty hard to understand so if you have a hard time understanding them, just comment and I'll try to probably make it easier.
Here are some code snippets:
For the first one:
std::string func(std::string& LValue) {
return static_cast<std::string&&>(LValue); // Does this cast it to an RValue and then reference collapsing happens causing it to become a LValue?
}
int main() {
std::string t = "Testing";
std::string& t1 = t;
func(t1);
}
For the second one:
std::string func(std::string& LValue) {
return static_cast<std::string&&>(LValue); //This casts it to a RValue. Does this turn it to a RValue and no reference collapsing happens resulting to a RValue?
}
int main() {
std::string t = "Testing";
std::string& t1 = t;
func(t1);
}