c++ - 排序时更改排序顺序是未定义的行为吗?

标签 c++ multithreading c++11

想象一下以下场景:

std::atomic<int>  values[10];
std::size_t      indices[10];

void sort() {
    std::iota(indices, indices+10, 0);

    std::sort(indices, indices+10,
        [&](size_t lhs, size_t rhs) { return values[lhs] < values[rhs]; });
}

在运行 sort() 时,另一个线程正在更改 values。这只会导致索引在之后无法正确排序,还是实际上是未定义的行为?

最佳答案

可能(见下文)这是未定义的行为;在实践中,我已经看到了普通的崩溃(对于容器边界外的访问),甚至只是因为不正确的(=不引起总排序)比较器,和<在排序时更改索引肯定无法导致总排序

有趣的是,该标准并未明确提及与此问题相关的未定义行为; C++11 §5.4 ¶3 只是指出

For algorithms other than those described in 25.4.3 to work correctly, comp has to induce a strict weak ordering on the values.

而且我没能在周围看到“正确工作”的正式定义;在整个第 25 章(描述 <algorithm> )中,甚至连“未定义”这个词都没有被提及。

关于c++ - 排序时更改排序顺序是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35502809/

相关文章:

c++ - 十六进制操作

c++ - std::wstring::find() 在 g++ 中损坏?

c++ - 如何规避 Symbian 命名约定?

javascript - Node.js 的缺点?

未捕获 Python SIGINT

C++ FANN fann_run 始终产生相同的输出

c++ - 什么是线程中的关键部分

c++ - 将引用和指针传递给 lambda

c++ - 编写类型特征以检测 Eigen 中的矩阵表达式

c++ - decltype 和 boost::variant - 检索当前值