c++ - 迭代器有效性和线程

标签 c++ c++11

假设我在 C++11 程序的主线程中构建了一个 std::set,用项目填充它并从中提取一个迭代器 it .之后,我从另一个线程开始修改集合,使元素只能添加到其中而不能删除。

it 的有效性是否在集合被修改时也得到保证,或者我是否应该认为 it 在集合被另一个线程的插入操作修改时无效?

最佳答案

来自第 23.2.1 节 [container.requirements.general]:

Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container.

对于诸如 std::set 的关联容器,第 23.2.4 节([associative.reqmts])说:

The insert and emplace members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

因此您的迭代器在插入其他项目后将保持有效。

然而,线程安全是完全不同的话题。

第 17.6.5.9 节([res.on.data.races])规定

Operations on iterators obtained by calling a standard library container or string member function may access the underlying container, but shall not modify it.

由于这会导致在更新容器时读取容器,在从另一个线程插入集合时使用 std::set 迭代器不一定安全 .您的实现可能会提供更有力的保证。

关于c++ - 迭代器有效性和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9006663/

相关文章:

c++ - 从我的 dylib 调用带有 std::string 参数的成员函数会产生 "Undefined symbols"错误

c++ - 为什么一个成员函数只存在一次,即使在一个包含多个 .h 文件中定义?

返回锁时的C++ 11 move

c++ - `f(void)` 表示 C++11 或 C 中没有参数?

c++11 - 仿函数的编译时检查

c++ - 使用 Opencv 调试断言失败 _pFirstBlock == pHead

c++ - 具有动态存储持续时间的 Lambda

c++ - 按时间从视频中获取帧(openCV)

c++ - 提升 iostreaming 过滤器获取空值

c# - 为什么 C++ 和 C# 的编译速度相差很大?