c – 为什么“return(str);”​​推断出与“return str”不同的类型?

参见英文答案 > Are parentheses around the result significant in a return statement?                                    12个
情况1:

#include <iostream>

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

int main()
{
        std::cout << fun() << std::endl;
}

在这里,程序在Gcc编译器中工作正常. decltype(auto)被推断为str的类型.

案例2:

#include <iostream>

decltype(auto) fun()
{
        std::string str = "In fun";
        return (str); // Why not working??
}

int main()
{
        std::cout << fun() << std::endl;
}

在这里,生成以下错误和分段错误:

In function 'decltype(auto) fun()':
prog.cc:5:21: warning: reference to local variable 'str' returned [-Wreturn-local-addr]
         std::string str = "In fun";
                     ^~~
Segmentation fault

为什么返回(str);给出分段错误?

解决方法:

decltype以两种不同的方式工作;当使用带有未表示的id-expression时,它会产生它所声明的确切类型(在第一种情况下它是std :: string).除此以外,

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.

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)是带括号的表达式,它是一个左值;然后它产生字符串&的类型.因此,您将返回对局部变量的引用,它将始终悬空.取消引用它会导致UB.

上一篇:c – 当对它们应用decltype时,哪些表达式产生引用类型?


下一篇:c – 使用decltype为函数生成的非类型模板参数