N3290 C++ 中的临时寿命草稿
N3290 C++ 草案第 12.2 节第 5 点第 10 行的一点。
第二个上下文是引用绑定到临时对象时。这 引用绑定到的临时对象或作为引用的临时对象 引用绑定到的子对象的完整对象 在引用的生命周期内持续存在,除了:
临时绑定到 new-initializer 中的引用 (5.3.4) 持续存在,直到包含以下内容的完整表达式完成 新的初始化程序。 [示例:
struct S { int mi; const std::pair
&议员; }; S a { 1, {2,3} }; S* p = new S{ 1, {2,3} };// 创建悬空引用 —结束示例] [注意:这可能会引入悬空引用, 并鼓励实施在此类情况下发出警告 案件。 ——尾注]
这是相对于C++03来说增加的一点。但这个例子对我来说无法理解。您能用其他例子解释这一点吗?
我知道什么是悬空引用和临时对象,并且 std::pair
保存两个可能不同数据类型的值。
A point from N3290 C++ draft, § 12.2, 5th point, line 10.
The second context is when a reference is bound to a temporary. The
temporary to which the reference is bound or the temporary that is the
complete object of a subobject to which the reference is bound
persists for the lifetime of the reference except:A temporary bound to a reference in a new-initializer (5.3.4)
persists until the completion of the full-expression containing the
new-initializer. [ Example:struct S { int mi; const std::pair<int,int>& mp; }; S a { 1, {2,3} }; S* p = new S{ 1, {2,3} };// Creates dangling reference
— end example ] [ Note: This may introduce a dangling reference,
and implementations are encouraged to issue a warning in such a
case. — end note ]
This is the added point when compared to C++03. But the example is not understandable for me. Can you please explain this point with any other example?
I know what dangling references and temporary objects are and that std::pair
holds two values of possibly different data types.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
临时对象通常仅持续到创建它们的表达式的末尾:
如果创建临时对象并将其绑定到引用。您也可以将其寿命延长到与它所绑定的引用相同的寿命。
此规则的例外情况是临时变量绑定到新初始值设定项中的引用时。
但在这里我们将新的临时对象绑定到成员
const std::pair& mp;
这是一个常量引用。但它所绑定的临时对象将在“;”处被销毁在上面的表达式中,因此 mp 将是对一个对象的引用,当您尝试在后续表达式中使用它时,该对象不再存在。
Temporaies in general last only to the end of the expression that they were created in:
If you create a temporary object and bind it to a reference. You extend its lifespan to the same lifespan of the reference it is bound too.
The exception to this rule is when the temporary is bound to a reference in a new initializer.
But here we are binding the new temporary object to the member
const std::pair<int,int>& mp;
This is a const reference. But the temporary object it is bound to will be destroyed at the ';' in the above expression so mp will be a reference to an object that no longer exists when you try and use it in subsequent expressions.