当我有简单的指针时,我可以像这样安全地包装数组:
p+=X; // p pointer p can point beyond end of array if(p>=array+array_size) p-=array_size; // forget about potential multiple wrap我可以安全地为任何可索引容器的迭代器做同样的事情,尤其是 双端队列?:
p+=x; if(p>=mydeque.end()) p-=mydeque.size(); // forget about potential multiple wrap换句话说:计算迭代器指向集合之外是否安全?
When I have simple pointer I can safely wrap array like this:
p+=X; // p pointer p can point beyond end of array if(p>=array+array_size) p-=array_size; // forget about potential multiple wrapcan I do the same safely for iterator over any indexable container, esp. deque?:
p+=x; if(p>=mydeque.end()) p-=mydeque.size(); // forget about potential multiple wrapIn other words: is it safe to take into calculations iterator pointing beyond collection?
最满意答案
你只能做p += X; 只要它仍然指向数组/容器内或数组/容器的末尾(第5.7节):
如果指针操作数和结果都指向同一个数组对象的元素,或者指向数组对象的最后一个元素,则评估不应产生溢出; 否则,行为未定义。
指针之间的比较也是如此。 它们必须指向相同的数组或指向结束的数组。 他们不能指出更多。
You can only do p += X; as long as it still points within the array/container or one past the end of the array/container (§5.7):
If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.
The same is true for comparisons between pointers. They must both be pointing at the same array or one past the end. They cannot be pointing further than that.
更多推荐
发布评论