I have watched a video about type deduction rules of auto and decltype explained by Scott Meyers ... He explained the following
// decltype(lvalue expr) => reference to the type of the expression
// decltype(lvalue name) => type of the name
I understand these rules ... but he didnt explain the following
// decltype(rvlaue expr) => ???
So I tried to understand it by practicing so I did the following
int x = 8;
int func(); // calling this function is rvlaue expr ...
decltype(32) t1 = 128; // Ok t1 is int
decltype(64) t2 = x; // Ok t2 is int
decltype(func()) t3 = x; // Ok t3 is int ... obviously
Now the magic
decltype(std::move(x)) t4 = x; // Error t4 is int&& ... compiler says
isn't std::move(x) a rvalue expression ? why decltype deducing t4 to int&& not just int like the examples above? What are the rules of decltype type deductions for rvalue expressions?
decltype
behaves differently based on the type it is used on
if the value category of expression is xvalue, then decltype yields T&&;
if the value category of expression is lvalue, then decltype yields T&;
if the value category of expression is prvalue, then decltype yields T.
As you can see it has two different behaviors for rvalues. If the rvalue is an xvalue then we get T&&
otherwise it is a prvalue and we get T
.
Now if we look at std::move
we see that it returns an xvalue
as the return is T&&
and not T
. So std::move(x)
is an xvalue and is correctly deduced to int&&
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With