正确使用BOOST_FOREACH? [英] Correct BOOST_FOREACH usage?
本文介绍了正确使用BOOST_FOREACH?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
BOOST_FOREACH
在使用,如下code安全吗?
BOOST_FOREACH(常量标准::字符串&放大器; STR,getStrings())
{
...
}...的std ::矢量<标准::字符串> getStrings()
{
的std ::矢量<标准::字符串>串;
strings.push_back(富);
...
返回字符串;
}
或者我应该在的抢容器的的副本调用 BOOST_FOREACH
,例如:
常量的std ::矢量<标准::字符串>字符串=的getString();
BOOST_FOREACH(常量标准::字符串&放大器; STR,字符串)
{
...
}
在第一个例子是没有任何危险 BOOST_FOREACH
最终可能会调用 getStrings()
多次<? / p>
解决方案
虽然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
, 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 callinggetStrings()
multiple times?解决方案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
这篇关于正确使用BOOST_FOREACH?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文