加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C 11/14并返回(…)vs返回

发布时间:2020-12-16 06:49:41 所属栏目:百科 来源:网络整理
导读:在C中,您可以编写一个返回语句,如下所示: return ( ... ); 这与更受欢迎的不同: return ... ; 特别是第一个版本返回包含该return语句的函数堆栈本地的东西的地址/引用. 既然为什么某些东西想要返回一个对那些在那时没有生命的东西的引用呢? 这个成语有什
在C中,您可以编写一个返回语句,如下所示:

return ( ... );

这与更受欢迎的不同:

return ... ;

特别是第一个版本返回包含该return语句的函数堆栈本地的东西的地址/引用.

既然为什么某些东西想要返回一个对那些在那时没有生命的东西的引用呢?

这个成语有什么用例?考虑到C 11和C 14的新流行语和功能,有不同的用法吗?

解决方法

前C 1y返回的括号版本是相同的,如果我们查看 C++11 draft standard节6.6跳转语句,返回的语法是:

return expressionopt ;

return braced-init-list ;

表达式可以是任何表达式,我们可以从5.1节中看到主表达式(强调我的前进):

A parenthesized expression is a primary expression whose type and
value are identical to those of the enclosed expression. The presence
of parentheses does not affect whether the expression is an lvalue.
The parenthesized expression can be used in exactly the same contexts
as those where the enclosed expression can be used,and with the same
meaning,except as otherwise indicated
.

在C 1y中,我们可以使用delctype(auto)来推断返回类型,这可以改变这种情况,我们可以从draft C++1y standard第7.1.6.4节自动说明符中看到:

When a variable declared using a placeholder type is initialized,or a
return statement occurs in a function declared with a return type that
contains a placeholder type,the deduced return type or variable type
is determined from the type of its initializer
.[…]

并包含以下示例:

auto x3a = i; // decltype(x3a) is int

decltype(auto) x3d = i; // decltype(x3d) is int

auto x4a = (i); // decltype(x4a) is int

decltype(auto) x4d = (i); // decltype(x4d) is int&

我们可以看到使用delctype(auto)和带括号的表达式时有区别.正在应用的规则来自第7.1.6.2节简单类型说明符第4段,其中说:

For an expression e,the type denoted by decltype(e) is defined as follows:

并包括以下项目符号:

— if e is an unparenthesized id-expression or an unparenthesized class
member access (5.2.5),decltype(e) is the type of the entity named by
e. If there is no such entity,or if e names a set of overloaded
functions,the program is ill-formed;

和:

— otherwise,if e is an lvalue,decltype(e) is T&,where T is the type of e;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读