为什么 "return (str);" 推导的类型与 C++ 中的 "return str;" 不同?
Why does "return (str);" deduce a different type than "return str;" in C++?
案例一:
#include <iostream>
decltype(auto) fun()
{
std::string str = "In fun";
return str;
}
int main()
{
std::cout << fun() << std::endl;
}
在这里,程序在 Gcc 编译器中运行良好。 decltype(auto)
被推断为 str
的类型。
案例二:
#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 表达式一起使用时,它会产生与声明方式完全相同的类型(在情况 1 中为 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)
是括号表达式,是左值;然后它产生 string&
的类型。所以你要返回对局部变量的引用,它总是悬空的。对其取消引用会导致 UB。
案例一:
#include <iostream>
decltype(auto) fun()
{
std::string str = "In fun";
return str;
}
int main()
{
std::cout << fun() << std::endl;
}
在这里,程序在 Gcc 编译器中运行良好。 decltype(auto)
被推断为 str
的类型。
案例二:
#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 表达式一起使用时,它会产生与声明方式完全相同的类型(在情况 1 中为 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)
anddecltype((x))
are often different types.
(str)
是括号表达式,是左值;然后它产生 string&
的类型。所以你要返回对局部变量的引用,它总是悬空的。对其取消引用会导致 UB。