为什么要“返回(str);”​​?推导出与“ return str;”不同的类型。在C ++中? [英] Why does "return (str);" deduce a different type than "return str;" in C++?

查看:201
本文介绍了为什么要“返回(str);”​​?推导出与“ return str;”不同的类型。在C ++中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

案例1:

#include <iostream>

decltype(auto) fun()
{
        std::string str = "In fun";
        return str;
}

int main()
{
        std::cout << fun() << std::endl;
}

在这里,程序在Gcc编译器中可以正常工作。 decltype(auto)被推导为 str 的类型。

Here, program work fine in Gcc Compiler. decltype(auto) is deduced to be the type of str.

案例2:

#include <iostream>

decltype(auto) fun()
{
        std::string str = "In fun";
        return (str); // Why not working??
}

int main()
{
        std::cout << fun() << std::endl;
}

此处,以下错误和分段错误生成:

Here, generated following error and Segmentation fault:

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中,它是 std :: string )。否则,


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

If the argument is any other expression of type T, and

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

a) if the value category of expression is xvalue, then decltype yields T&&;

b)如果表达式的值类别为lvalue,则十进制类型产生
T& ;;

b) if the value category of expression is lvalue, then decltype yields T&;

c)如果表达式的值类别为prvalue,则十进制类型
产生T。

c) if the value category of expression is prvalue, then decltype yields T.


请注意,如果对象的名称是用括号括起来,它被视为普通的左值表达式,因此 decltype(x) decltype((x))是通常是不同的类型。

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。

(str) is a parenthesized expression, and it's an lvalue; then it yields the type of string&. So you're returning a reference to local variable, it'll always be dangled. Dereference on it leads to UB.

这篇关于为什么要“返回(str);”​​?推导出与“ return str;”不同的类型。在C ++中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆