[英]array iterator not dereferencable error
There is a sample code that occurs the error as bellows. 有一个示例代码,该错误以波纹管形式出现。 In release mode, it works and prints five '-'.
在释放模式下,它可以工作并打印五个“-”。 However, in debug mode, it doesn't work and occurs a runtime error that is 'array iterator not dereferencable'.
但是,在调试模式下,它不起作用,并会发生“数组迭代器不可取消引用”的运行时错误。
environment details : Windows 7 64bit Visual Studio 2015 update 2 环境详细信息:Windows 7 64位Visual Studio 2015更新2
I don't know why there are deferences between release and debug mode. 我不知道为什么发布和调试模式之间会有区别。 Thanks in advance.
提前致谢。
#include <iostream>
#include <array>
static bool operator != (int * a, std::array<int, 5>::iterator &b)
{
return a != &(*b);
}
int main(void)
{
std::array<int, 5> arr = { 0,0,0,0,0 };
for (auto* it = &arr[0]; it != arr.end(); it++)
{
std::cout << "-" << std::endl;
}
return 0;
}
You call *b
when b
is arr.end()
. 当
b
为arr.end()
时,您调用*b
。 This causes undefined behaviour . 这会导致不确定的行为 。 You can only use
*
on an iterator that refers to an element of the array. 您只能在引用数组元素的迭代器上使用
*
。
Overloading operators requires that at least one operand be a class or enumeration type. 重载运算符要求至少一个操作数是类或枚举类型。
std::array<int, 5>::iterator
is just a typedef for int*
, which is a built-in type. std::array<int, 5>::iterator
只是int*
的typedef,它是内置类型。 You don't need to overload the comparison operator since the comparisons between pointers are already well-defined. 您不需要重载比较运算符,因为指针之间的比较已经明确定义。
References: 参考文献:
https://isocpp.org/wiki/faq/intrinsic-types#intrinsics-and-operator-overloading https://isocpp.org/wiki/faq/intrinsic-types#intrinsics-and-operator-overloading
https://gcc.gnu.org/onlinedocs/libstdc++/manual/iterators.html https://gcc.gnu.org/onlinedocs/libstdc++/manual/iterators.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.