Case 1:
#include
decltype(auto) fun()
{
std::string str = \"In fun\";
return str;
}
int main()
{
std:
decltype works in two different ways; when using with unparenthesized id-expression, it yields the exact type how it's declared (in case 1 it's std::string
). Otherwise,
If the argument is any other expression of type T, and
a) if the value category of expression is xvalue, then decltype yields T&&;
b) if the value category of expression is lvalue, then decltype yields T&;
c) if the value category of expression is prvalue, then decltype yields T.
and
Note that if the name of an object is parenthesized, it is treated as an ordinary lvalue expression, thus
decltype(x)
anddecltype((x))
are often different types.
(str)
is a parenthesized expression, and it's an lvalue; then it yields the type of string&
. So you're returning a reference to local variable, it'll always be dangled. Dereference on it leads to UB.