【问题标题】:Why does "return (str);" deduce a different type than "return str;" in C++?为什么“返回(str);”推断出与“return str;”不同的类型在 C++ 中?
【发布时间】: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&amp;?这是个有趣的问题。
  • @Picnix_ 谢谢。票数最高的答案很好地回答了我的问题。
  • @MartinBonnersupportsMonica 请重新打开这个问题。它没有重复,因为通过关注c++,它更加具体和有用。非常古老的链接问题stackoverflow.com/questions/4762662/… 是关于cc++ 同时并没有那么有用。

标签: c++ c++14 decltype return-type-deduction


【解决方案1】:

decltype 有两种不同的工作方式;当与未加括号的 id-expression 一起使用时,它会产生其声明方式的确切类型(在情况 1 中为 std::string)。否则,

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

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

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

c) 如果表达式的值类别是prvalue,那么decltype 产生 T。

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

(str) 是一个带括号的表达式,它是一个左值;然后它产生string&amp; 的类型。所以你返回一个对局部变量的引用,它总是悬空的。对其取消引用会导致 UB。

【讨论】:

  • 请注意,这也是使用decltype(auto)的结果。如果你使用普通的auto 作为函数的返回类型,这不会有问题。
猜你喜欢
  • 2018-10-24
  • 2021-11-07
  • 1970-01-01
  • 2017-12-13
  • 2017-11-21
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多