简体   繁体   中英

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:

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. 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):

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.

So the temporary value_type() will be bound to val and will persist for the duration of the constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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