我们在循环中追加新元素的列表的 for(auto ...) 是否保证对所有元素起作用?

Is a for(auto ...) of list where we append new elements within the loop guaranteed to work against all the elements?

我有一个带有 f_next 字段的 class,如下所示:

class process
{
public:
    typedef std::shared_ptr<process> pointer_t;
    typedef std::list<pointer_t> list_t;

    void add_next_process(pointer_t p);
    void wait();

private:
    list_t f_next = list_t();
};

add_next_process() 只是将 p 附加到 f_next:

f_next.push_back(p);

因此,wait() 必须收集所有进程并等待所有进程。我想避免递归,而是生成所有 f_next 的列表,如下所示:

list_t n(f_next);
for(auto & it : n)
{
    n.insert(n.end(), it->f_next.begin(), it->f_next.end());
}

一旦 for() 循环退出,n 是否保证包含所有项目?

我知道std::list::insert()不会改变迭代器:

No iterators or references are invalidated.

但我想知道 for(auto ...) 是否会继续处理我在此过程中附加的所有项目。

For-range 只是在迭代器上运行的经典 for 循环的语法糖。 只要您的容器实现了开始和结束(或者您有自由重载),并且在过程中不使迭代器无效,这在技术上应该没问题。 另一件事是这是否是一个好的和可维护的想法。

C++17 之前:

auto && __range = range-expression ;
for (auto __begin = begin_expr, __end = end_expr; __begin != __end; ++__begin) {
  range-declaration = *__begin;
  loop-statement
}

来自 C++17:

auto && __range = range-expression ;
auto __begin = begin_expr ;
auto __end = end_expr ;
for ( ; __begin != __end; ++__begin) {
  range-declaration = *__begin;
  loop-statement
}