简体   繁体   English

负数导致std :: multimap end()迭代器的std :: advance崩溃

[英]std::advance of std::multimap end() iterator by negative number crashes

My app crashed on this operation: 我的应用在执行此操作时崩溃:

std::multimap<int, std::string, std::greater<int>> mm;
// insert elements
auto it = mm.end();
std::advance(it, -(mm.size() - 7));

Here is the message of crash: 这是当机的讯息:

Expression: map/set iterator not incrementable

What is the problem? 问题是什么?

EDIT: When I wrote just -1 instead of -(mm.size() - 7) it did not crash, why? 编辑:当我只写-1而不是-(mm.size() - 7)它没有崩溃,为什么? Please consider that when I debug mm.size() is 8. 请考虑当我调试mm.size()为8时。

EDIT 2: When I write std::advance(it, -(static_cast<int>(scoresMap.size()) - 7)); 编辑2:当我写std::advance(it, -(static_cast<int>(scoresMap.size()) - 7)); it works. 有用。 It is because of the size type of the multimap, but still cannot guess what is the reason. 这是因为多图的大小类型,但仍然无法猜测是什么原因。

The expresion (mm.size() - 7) produces an unsigned value, std::size_t. (mm.size() - 7)产生一个无符号值std :: size_t。 The unsigned value is then negated, and according to recent C++ draft spec (N3690): 然后,根据最近的C ++规范草案(N3690),将无符号值取反:

The operand of the unary - operator shall have arithmetic or unscoped enumeration type and the result is the negation of its operand. 一元运算符的操作数应具有算术或无作用域的枚举类型,其结果是其操作数的取反。 Integral promotion is performed on integral or enumeration operands. 积分提升是对整数或枚举操作数执行的。 The negative of an unsigned quantity is computed by subtracting its value from 2 n , where n is the number of bits in the promoted operand. 无符号数量的负数是通过从2 n中减去其值来计算的,其中n是提升操作数中的位数。 The type of the result is the type of the promoted operand. 结果的类型是提升操作数的类型。

the value being provided to std::advance could be converted to some value larger than mm.size() due to the negation rules of unsigned types. 由于无符号类型的取反规则,提供给std::advance值可以转换为大于mm.size()某个值。

The second expression in your edit, static_cast<int>(scoresMap.size() - 7) , changes the value to a signed type, int. 编辑中的第二个表达式static_cast<int>(scoresMap.size() - 7)将值更改为带符号类型int。 Negating that value will get the desired value, however, the static_cast has undefined behavior if scoresMap.size() - 7 returns a value larger than std::numeric_limits<int>::max() . 取反该值将获得所需的值,但是,如果scoresMap.size() - 7返回的值大于std::numeric_limits<int>::max() ,则static_cast具有未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM