If a function returns decltype(auto) and it returns a local variable of type int&&, why does the return type is int&?
If I cast the variable to its own type, then the return type is what I expect (int&&)
#include <utility>
namespace{
auto i = 5;
auto j = 5;
decltype(auto) foo1(){
int&& ret = std::move(i);
return ret;
}
decltype(auto) foo2(){
int&& ret = std::move(j);
return static_cast<decltype(ret)>(ret);
}
}
int main(){
static_assert(std::is_same_v<decltype(foo1()),int&>);
static_assert(std::is_same_v<decltype(foo2()),int&&>);
}
This seems to be a bug in GCC. Since decltype(ret)
is int&&
, foo1
should have return type int&&
. However, this immediately renders foo1
ill-formed, since a function that returns int&&
cannot have its return value initialized from ret
, which is an lvalue (you would need std::move
to make it work properly). Note that Clang gets this right (see link in comments to the question).
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