案例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);会产生分割错误?
发布于 2018-06-04 05:50:46
decltype以两种不同的方式工作;当使用不带括号的id-表达式时,它会得到声明它的确切类型(在第1种情况下,它是std::string)。否则,
如果参数是T类型的任何其他表达式,并且 如果表达式的值类别为x值,则解密类型将产生T&; b)如果表达式的值范畴为lvalue,则解密类型产生T&; c)如果表达式的值类别为prvalue,则解密类型将产生T。
和
注意,如果对象的名称为括号,则将其视为一个普通的lvalue表达式,因此
decltype(x)和decltype((x))通常是不同的类型。
(str)是一个带括号的表达式,它是一个lvalue;然后它生成string&的类型。所以你要返回一个局部变量的引用,它总是在悬空中。会导致UB的出现。
https://stackoverflow.com/questions/50674046
复制相似问题