Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it best practice to assign a std::vector<T> to a variable before iteration?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading