代码之家  ›  专栏  ›  技术社区  ›  Rob

正确使用boost?

  •  4
  • Rob  · 技术社区  · 15 年前

    使用时 BOOST_FOREACH ,以下代码安全吗?

    BOOST_FOREACH (const std::string& str, getStrings())
    {
      ...
    }
    
    ...
    
    std::vector<std::string> getStrings()
    {
      std::vector<std::string> strings;
      strings.push_back("Foo");
      ...
      return strings;
    } 
    

    还是要我拿个集装箱的副本 之前 打电话 助推器前缘 ,例如:

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

    在第一个例子中,是否存在 助推器前缘 可能会打电话 getStrings() 多次?

    2 回复  |  直到 15 年前
        1
  •  14
  •   Nikola Smiljanić    15 年前

    尽管Boost ForEach是一个宏, 这是一个非常好的行为。 它精确地计算其参数 一次,不会带来令人不快的惊喜

        2
  •  1
  •   Tristan    15 年前

    你可以使用 BOOST_FOREACH 无论何时你想要以一种简洁的方式穿越事物。考虑使用boost.range遍历自己的类。

    我使用 助推器前缘 防止代码污染 for 语句、迭代器(声明初始化等…) 我尽可能多地使用stl算法(cogweels)和boost lambda表达式(glue)。它使代码比自定义for循环更易于理解。