tags:

views:

128

answers:

2

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?

+6  A: 

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ć
Concise, but impressively adequate answer ! (+1, of course)
Benoît
It's a quote from their documentation :)
Nikola Smiljanić
A: 

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