简体   繁体   中英

The right way capturing prvalue in C++11

What is the correct practice capturing return value of boost::make_iterator_range in following scenarios:

  1. When used in range based for loop:

     for (auto&& val : boost::make_iterator_range(...))// <-- is `auto&&` the right way? 
  2. When used as formal parameter:

     DoStuff(boost::make_iterator_range(...)); template<class Iterator> void DoStuff(Iterator&& it){}// <-- is Iterator&& the right way? 
for (auto&& val : boost::make_iterator_range(...))//  <-- is `auto&&` the right way?

The return value of make_iterator_range is not stored in val . val simply stores the return value of the dereferencing of the iterators: the element, not the entire range.

auto&& creates a forwarding reference to the element.

DoStuff(boost::make_iterator_range(...));

template<class Iterator>
void DoStuff(Iterator&& it){}//  <-- is Iterator&& the right way?

Using the name Iterator belies a misunderstanding: make_itetator_range is not an iterator, it is a range defined by iterators.

template<class Range>
void DoStuff(Range&& r){}

This does not change the behaviour of the code, but it was like having a variable of type int named Double : pointlessly or aggressively confusing.

In any case, Range&& r in this context is also a forwarding reference.

A forwarding reference in a type deduction context can bind to either an lvalue or rvalue. It can cause reference lifetime extension as well.


In both of these situations, auto&& and Range&& are reasonable approaches, but so would auto const& , auto& or auto in the first case, and in the second Range const& or Range have their advantages. They just mean different things.

So your solutions are one way that can be right, but there is no "one right way" for what to put there. I use forwarding references by default, but that is a matter of taste: others might choose to default to const& or values. And in some contexts, auto& would be proper (where your loop modifies the value and intends that modification to persist).

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