案例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
为什么return (str);
导致分段错误?
decltype
以两种不同的方式工作;与非括号化的id-expression一起使用时,它会产生确切的声明类型(在情况1中为decltype
)。否则,
如果参数是类型T的任何其他表达式,并且
a)如果表达式的值类别为xvalue,则decltype产生T &&;
b)如果表达式的值类别为左值,则decltype产生T&;
c)如果表达式的值类别是prvalue,则为decltype产生T。
和
[注意,如果将对象的名称括起来,则将其视为普通的左值表达式,因此
std::string
和decltype(x)
通常是不同的类型。
decltype((x))
是带括号的表达式,它是一个左值;然后得出(str)
的类型。因此,您将返回对局部变量的引用,它将始终处于悬挂状态。对它的取消引用导致UB。