Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct BOOST_FOREACH usage?

Tags:

c++

foreach

boost

When using BOOST_FOREACH, is the following code safe?

BOOST_FOREACH (const std::string& str, getStrings())
{
  ...
}

...

std::vector<std::string> getStrings()
{
  std::vector<std::string> strings;
  strings.push_back("Foo");
  ...
  return strings;
} 

Or should I grab a copy of the container before calling BOOST_FOREACH, e.g.:

const std::vector<std::string> strings = getString();
BOOST_FOREACH (const std::string& str, strings)
{
  ...
}

In the first example is there any danger that BOOST_FOREACH could end up calling getStrings() multiple times?

like image 613
Rob Avatar asked Dec 08 '22 04:12

Rob


1 Answers

And although BOOST_FOREACH is a macro, it is a remarkably well-behaved one. It evaluates its arguments exactly once, leading to no nasty surprises

like image 105
Nikola Smiljanić Avatar answered Dec 30 '22 20:12

Nikola Smiljanić