我的方法如下:
#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.
强调我的
原文地址:https://www.jb51.cc/c/110672.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。