【发布时间】:2018-11-13 09:40:42
【问题描述】:
案例 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); 给出分段错误?
【问题讨论】:
-
警告信息应该告诉你所有你需要知道的。
-
我想你搜索类似的东西:stackoverflow.com/questions/4762662/…
-
@Someprogrammerdude 这解释了为什么会出现段错误-但为什么
return str;会推断出std::string,但return (str);会推断出std::string&?这是个有趣的问题。 -
@Picnix_ 谢谢。票数最高的答案很好地回答了我的问题。
-
@MartinBonnersupportsMonica 请重新打开这个问题。它没有重复,因为通过关注
c++,它更加具体和有用。非常古老的链接问题stackoverflow.com/questions/4762662/… 是关于c和c++同时并没有那么有用。
标签: c++ c++14 decltype return-type-deduction