Proper use of BOOST_FOREACH?

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 , for example:

 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 might call getStrings() several times?

+4
source share
2 answers

And while BOOST_FOREACH is a macro, it is remarkably good. He accurately evaluates his arguments once, which does not lead to unpleasant surprises.

+14
source

You can use BOOST_FOREACH whenever you want to easily navigate things. Consider Boost.Range to traverse your own classes using BOOST_FOREACH.

I use BOOST_FOREACH to prevent code pollution with for statements, iterators (initializing declarations, etc.). I use STL algorithms (cogweels) with impulse lambda expressions (glue) as much as I can. This makes the code more understandable than the custom for the loop.

+1
source

All Articles