Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

c++ - 为什么在C ++中,“ return(str);”??得出的类型不同于“ return str;”?(Why does “return (str);” deduce a different type than “return str;” in C++?)

Case 1:

(情况1:)

#include <iostream>

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

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

Here, program work fine in Gcc Compiler.

(在这里,程序可以在Gcc编译器中正常运行。)

decltype(auto) is deduced to be the type of str .

(decltype(auto)被推导为str的类型。)

Case 2:

(情况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

Why does return (str);

(为什么return (str);)

giving segmentation fault?

(给分割错误?)

  ask by msc translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

decltype works in two different ways;

(decltype以两种不同的方式起作用;)

when using with unparenthesized id-expression, it yields the exact type how it's declared (in case 1 it's std::string ).

(与非括号化的id-expression一起使用时,它会产生确切的声明类型(在情况1中为std::string )。)

Otherwise,

(除此以外,)

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

(如果参数是类型T的任何其他表达式,则)

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

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

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

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

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

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

and

(和)

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.

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

(str) is a parenthesized expression, and it's an lvalue;

((str)是带括号的表达式,它是一个左值;)

then it yields the type of string& .

(然后产生string&的类型。)

So you're returning a reference to local variable, it'll always be dangled.

(因此,您将返回对局部变量的引用,它将始终处于悬挂状态。)

Dereference on it leads to UB.

(对其取消引用将导致UB。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...