您的比较对象没有违反Compare的行为的任何陈述的先决条件,这是一个标准缺陷.您没有在对象上调用任何非const操作,而是在调用了非const复制构造函数.确实没有涵盖.但是,此特定示例 的行为是未定义的,其原因有所不同:您的比较由于破坏了其所有元素而无法成为严格的弱命令-与 [algo.sorting]/3 . I was examining old deprecated code that used std::auto_ptr and I was wondering if this is an undefined behaviour:std::vector<std::auto_ptr<int>> v;//populate v with elements...std::sort(v.begin(), v.end(), [](auto a, auto b) {/* some reasonable "less" comparison */});Now, this kind of comparator of course empties the collection, because copy constructor of std::auto_ptr takes non-const reference. I was looking for a rule in standard that mandates such behaviour, but all I was able to find is this:But this is at least not enough, because comparator that takes two std::auto_ptr by value does not "apply any non-constant function through the dereferenced iterator" - copy constructor is not applied by comparator itself.Moreover, very same issue applies to superclass of Compare - in [algorithms.requirements#7] paragraph about BinaryPredicate we can read almost the same sentence: Which means, if issue exists, will be propagated to many other algorithms.My question is: Is comparator, that takes std::auto_ptr arguments by value, violates requirements for std::sort making call to it an undefined behaviour, or this code is fine, just works wrong ; )? Or, maybe this is an issue in C++ Standard Library specification?Read more:http://eel.is/c++draft/alg.sorting#2.sentence-4http://eel.is/c++draft/algorithms.requirements#7.sentence-4http://www.eel.is/c++draft/sorthttp://en.cppreference.com/w/cpp/algorithm/sorthttp://en.cppreference.com/w/cpp/concept/Compare 解决方案 This is basically LWG 3031.Your comparison object doesn't violate any of the stated preconditions of how Compare should behave, which is a standard defect. You're not invoking any non-const operations on the objects, you're invoking a non-const copy constructor. That isn't really covered.However, this particular example is undefined behavior for a different reason: your comparison, due to its destroying all of its elements, will fail to be a strict weak order - which runs afoul of [algo.sorting]/3. 这篇关于是否要求STL中使用的Comp比较器从不更改STL中的比较对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
11-03 10:07