简体   繁体   English

将临时右值绑定到std :: vector构造函数中的引用左值

[英]Bind temporary rvalue to reference lvalue in std::vector constructors

Until now, I thought that we cannot pass a temporary rvalue to a lvalue reference. 到目前为止,我认为我们不能将临时右值传递给左值引用。 But just recently, I took a closer look on the fill constructor of std::vector: 但是就在最近,我仔细研究了std :: vector的fill构造函数:

explicit vector (size_type n, const value_type& val = value_type(),
                 const allocator_type& alloc = allocator_type());

const value_type& val is a reference lvalue and = value_type() is a anonymous rvalue, in my understanding. 在我的理解中, const value_type& val是一个引用左值,而= value_type()是一个匿名右值。 Why is it possible? 为什么可能呢? Isn't the temporary rvalue immediately destroyed, so that the reference has nothing to point to? 临时右值是否会立即被销毁,以便引用没有指向?

The relevant part of the standard is in [class.temporary] ( §12.2/5 in N4140): 该标准的相关部分在[class.temporary]中( §12.2/5 ):

A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call. 在函数调用(5.2.2)中,绑定到参考参数的临时绑定将一直持续到包含该调用的完整表达式完成。

So the temporary value_type() will be bound to val and will persist for the duration of the constructor. 因此,临时value_type()将绑定到val ,并将在构造函数期间持续存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM