4

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?

Rob
  • 76,700
  • 56
  • 158
  • 197

2 Answers2

14

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

Nikola Smiljanić
  • 26,745
  • 6
  • 48
  • 60
1

You can use BOOST_FOREACH whenever you want to traverse things, in a concise manner. Consider Boost.Range to traverse your own classes with BOOST_FOREACH.

I use BOOST_FOREACH to prevent pollution of code with for statements, iterators ( declaration initilization, etc...) I use STL algorithms (cogweels) with boost lambda expressions (the glue) as much I can. It makes the code more much understandable than a custom for loop.

Tristan
  • 126
  • 1
  • 5