Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decltype(auto) function return type does not deduce && types

Tags:

c++

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&&>);
}
like image 629
Hui Avatar asked Oct 16 '22 15:10

Hui


1 Answers

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).

like image 56
Brian Bi Avatar answered Oct 23 '22 09:10

Brian Bi