I’m working with a smart pointer which returns a std::vector<T> over which I want to iterate using a for loop.
Are there any disadvantages to returning the std::vector<T> directly within the for loop as opposed to assigning it to a variable before the loop?
For example, instead of this:
const myClass& vec = myPtr->getVec();
for (const itemPtr& item : vec)
{
...
}
Can I safely do this?:
for (const itemPtr& item : myPtr->getVec())
{
...
}
>Solution :
In fact, a binding to a reference is part of declared range for-loop functionality, only it uses an rvalue reference (result could have been a temporary):
//for ( init-statement (optional) range-declaration : range-expression )
// loop-statement
{
init-statement
auto && __range = range-expression ;
auto __begin = begin-expr ;
auto __end = end-expr ;
for ( ; __begin != __end; ++__begin)
{
range-declaration = *__begin;
loop-statement
}
}