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

c – 何时返回rvalue引用导致未定义的行为?

发布时间:2020-12-16 09:54:46 所属栏目:百科 来源:网络整理
导读:在Stack Overflow回答 here中,Kerrek发布以下代码. Foo g(){ Foo y; // return y; // error: cannot bind ‘Foo’ lvalue to ‘Foo’ return std::move(y); // OK type-wise (but undefined behaviour,thanks @GMNG)} GManNickG指出这会导致未定义的行为. 克
在Stack Overflow回答 here中,Kerrek发布以下代码.

Foo && g()
{
    Foo y;
    // return y;         // error: cannot bind ‘Foo’ lvalue to ‘Foo&&’
    return std::move(y); // OK type-wise (but undefined behaviour,thanks @GMNG)
}

GManNickG指出这会导致未定义的行为.

克雷克补充道

True; you don’t really return && from anything but forward and move.
It’s a contrived example.

令我困惑的是,C 11标准使用函数调用,该函数调用返回rvalue引用作为xvalue表达式的示例.

An xvalue (an “eXpiring” value) also refers to an object,usually near
the end of its lifetime (so that its resources may be moved,for
example). An xvalue is the result of certain kinds of expressions
involving rvalue references (8.3.2). [ Example: The result of calling
a function whose return type is an rvalue reference is an xvalue. —end
example ]

那么,当确实在未定义的行为中返回rvalue引用结果时?它是否总是导致未定义的行为,除了std :: move和std :: forward并且标准只是简洁?或者您是否必须访问未定义行为的返回值才能生成结果?

*“何时”是指“在什么情况下”.我意识到这里没有有意义的时间概念.

解决方法

转换为引用不会延长局部变量的生命周期.

因此,在本地过期后使用对本地的引用是未定义的行为.

由于本地函数完成时到期,因此无法使用返回值.

std :: move或std :: forward接受引用,并返回可能不同类型的引用.既没有延长他们争论的生命周期,也没有返回对他们自己身体的本地变量的引用.

这里的UB不返回右值引用,而是返回基于对象的生命周期.它在使用时发生,而不是在施放或返回时发生.

也就是说,返回一个右值引用几乎不是一个好主意:返回一个副本.副本可以参与终身延期.例外情况是你在编写类似forward_as_tuple的东西.

(编辑:李大同)

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

    推荐文章
      热点阅读