gpt4 book ai didi

c++ - 堆栈上 char 的有效迭代器范围

转载 作者:行者123 更新时间:2023-11-30 01:19:03 24 4
gpt4 key购买 nike

#include <iostream>
#include <vector>

int main()
{
char c = 'c';
std::vector<char> v(&c, &c + 1);

std::cout << v.size() << '\n'; // 1

return 0;

}

编译器说这个程序没问题。这是否意味着 &c, &c + 1 对是有效的迭代器范围?是否没有 &c + 1 换行的边缘情况? (我真的无法想象 &c + 1 可能会换行,但它的含义让我很困扰!)

最佳答案

引用标准(强调我的),

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. When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and i − n-th elements of the array object, provided they exist. 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.

(ISO/IEC 14882:2011 §5.7 加法运算符 [expr.add] 第 4-5 段)

所以是的,这是完全符合犹太洁食标准的,就像您使用只有一个元素的数组一样。 &c + 1含义就像它说的那样:“最后一个元素之后的一个”。它不指向您被允许访问的任何对象,但以其他方式使用它是有效的。

关于c++ - 堆栈上 char 的有效迭代器范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21505447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com