Why does “return (str);” deduce a different type than “return str;” in C++?

前端 未结 1 1014
北海茫月
北海茫月 2021-02-07 23:04

Case 1:

#include 

decltype(auto) fun()
{
        std::string str = \"In fun\";
        return str;
}

int main()
{
        std:         


        
相关标签:
1条回答
  • 2021-02-07 23:41

    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) and decltype((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.

    0 讨论(0)
提交回复
热议问题