C++错误使用迭代器超出引用范围问题及解决方案

这篇文章主要介绍了C++错误使用迭代器超出引用范围分析与解决,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

前言

今天在调用一个URI解析库的时候,在clang的编译器上代码能正常编译,在visual studio就提示迭代器的错误了

相关错误

cannot increment value-initialized string_view iterator
cannot dereference end string_view iterator
cannot increment string_view iterator past end
string iterator not dereferencable" you’ll get "cannot dereference string iterator because it is out of range (e.g. an end iterator)

错误截图

错误代码块

错误原因

if (end_ptr != &*auth_string.end()) { return { authority, uri::Error::InvalidPort, auth_string }; }

end()方法将迭代器返回到最后一个元素之后,指向字符串最后一个字符下一个位置。由于它并不指向实际的字符,因此不能对该迭代器进行解引用操作。

如果想访问最后一个元素,应该使用

  • string.end() - 1:注意,该语句仅适用于非空字符串,否则将会越界访问
  • string.back()
  • string.at(string.size() - 1)

解决方案

方法1(推荐)

if (--end_ptr != &(auth_string.back())) { return { authority, uri::Error::InvalidPort, auth_string }; }

方法2

if (--end_ptr != &*--auth_string.end()) { return { authority, uri::Error::InvalidPort, auth_string }; }

方法3

if (--end_ptr != &(auth_string.at(auth_string.size() - 1))) { return { authority, uri::Error::InvalidPort, auth_string }; }

Visual Studio 更新日志

https://learn.microsoft.com/en-us/cpp/overview/what-s-new-for-cpp-2017?view=msvc-170#visual-studio-2017-rtm-version-150

  • Minor basic_string _ITERATOR_DEBUG_LEVEL != 0 diagnostics improvements. When an IDL check gets tripped in string machinery, it will now report the specific behavior that caused the trip. For example, instead of “string iterator not dereferencable” you’ll get “cannot dereference string iterator because it is out of range (e.g. an end iterator)”.
  • 次要 basic_string_ITERATOR_DEBUG_LEVEL != 0 诊断改进。 当 IDL 检查在字符串机制中失误时,它现在会报告导致失误的特定行为。 例如,现在会收到“无法取消引用字符串迭代器,因为其已超出范围(例如末尾迭代器)”,而不是“字符串迭代器不可取消引用”。

在更新日志中已经告诉了我们错误的原因了

到此这篇关于C++错误使用迭代器超出引用范围分析与解决的文章就介绍到这了,更多相关C++迭代器超出引用范围内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是C++错误使用迭代器超出引用范围问题及解决方案的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言