我的方法如下:
#include <iostream> #include <vector> template<typename Iter> void iterate_over(Iter begin,Iter end){ for(auto i = begin; i != end; ++i){ std::cout << *i << std::endl; } } int main(){ std::vector<int> a{1,2,3,4}; iterate_over(a.cbegin(),a.cend()); int b = 5; iterate_over(&b,std::next(&b)); }
这似乎在g 5.2中正常工作,但我想知道这是否是实际定义的行为以及是否存在任何潜在问题?
解决方法
For the purposes of these operators,a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.
因此,单个对象被视为长度为1的数组.然后我们有[expr.add] / 5
[…]Moreover,if the expression P points to the last element of an array object,the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object,the expression (Q)-1 points to the last element of the array object. 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.
强调我的
因此,由于第一个数组元素也是最后一个数组元素,并且向最后一个数组元素添加1会为您提供一个超过该对象的元素,这是合法的.