为什么“return (str);”推导出与“return str;”不同的类型在 C++ 中?

2023-12-22

Case 1:

#include <iostream>

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

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

在这里,程序在 Gcc 编译器中运行良好。decltype(auto)被推导为以下类型str.

Case 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

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


decltype https://en.cppreference.com/w/cpp/language/decltype以两种不同的方式工作;当与不带括号的 id 表达式一起使用时,它会生成其声明方式的确切类型(在情况 1 中,它是std::string)。否则,

如果参数是 T 类型的任何其他表达式,并且

a) 如果表达式的值类别是 xvalue,则 decltype 产生 T&&;

b) 如果表达式的值类别是左值,则 decltype 产生 T&;

c) 如果表达式的值类别是纯右值,则 decltype 产生 T。

and

请注意,如果对象的名称带有括号,则它将被视为普通的左值表达式,因此decltype(x) and decltype((x))通常是不同的类型。

(str)是一个带括号的表达式,并且它是一个左值;然后它产生的类型string&。因此,您返回的是对局部变量的引用,它始终是悬空的。对它的取消引用会导致 UB。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么“return (str);”推导出与“return str;”不同的类型在 C++ 中? 的相关文章

随机推荐