微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 迭代单个左值

我想将一个左值传递给一个需要一对迭代器的函数,并且它就像我将一对迭代器传递给只包含这个值的范围一样.

我的方法如下:

#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中正常工作,但我想知道这是否是实际定义的行为以及是否存在任何潜在问题?

解决方法

是的,这是定义的行为.首先我们来自[expr.add] / 4

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会为您提供一个超过该对象的元素,这是合法的.

原文地址:https://www.jb51.cc/c/110672.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐