The following gives a compiler error:
#include <string>
const std::string& get_name();
int main(){
auto&& name1 = get_name();//should bind to whatever
const auto& name2 = get_name();//also ok
const auto&& name3 = get_name();//<-not ok, why ?
return 0;
}
Link to godbolt: https://godbolt.org/z/l6IQQ7
If I use const auto&
it compiles - but that will not bind to value.
auto&&
will be bind to anything so that naturally works as well.
However, what is the logic behind const auto&&
not binding in this case ?
I know auto&&
will preserve the constness - but is there a way to be const
explicit and at the same time be reference/value agnostic ?
Motivation:
For 'normal programming work' inside functions etc. it would be great to be able to say something like: "I do not care if it's a value or reference - but I do not change it for the rest of the function".
This should be possible given current language.
Related question: Why adding `const` makes the universal reference as rvalue
auto
in this case, I think we can close it? – Femme