C++錯誤使用迭代器超出引用范圍問題及解決方案
前言
今天在調(diào)用一個URI解析庫的時候,在clang的編譯器上代碼能正常編譯,在visual studio就提示迭代器的錯誤了
相關(guān)錯誤
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()
方法將迭代器返回到最后一個元素之后,指向字符串最后一個字符的下一個位置。由于它并不指向?qū)嶋H的字符,因此不能對該迭代器進行解引用操作。
如果想訪問最后一個元素,應(yīng)該使用
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 更新日志
- 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 檢查在字符串機制中失誤時,它現(xiàn)在會報告導(dǎo)致失誤的特定行為。 例如,現(xiàn)在會收到“無法取消引用字符串迭代器,因為其已超出范圍(例如末尾迭代器)”,而不是“字符串迭代器不可取消引用”。
在更新日志中已經(jīng)告訴了我們錯誤的原因了
到此這篇關(guān)于C++錯誤使用迭代器超出引用范圍分析與解決的文章就介紹到這了,更多相關(guān)C++迭代器超出引用范圍內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
cin.get()和cin.getline()之間的區(qū)別
以下是對cin.get()和cin.getline()的區(qū)別進行了詳細的分析介紹,需要的朋友可以過來參考下,希望對大家有所幫助2013-09-09淺談C語言共用體和與結(jié)構(gòu)體的區(qū)別
下面小編就為大家?guī)硪黄獪\談C語言共用體和與結(jié)構(gòu)體的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02C++實現(xiàn)LeetCode(7.翻轉(zhuǎn)整數(shù))
這篇文章主要介紹了C++實現(xiàn)LeetCode(7.翻轉(zhuǎn)整數(shù)),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07深入學(xué)習(xí)C語言mmap和shm*的使用方法技巧
本文將詳細介紹mmap和shm的工作原理,包括它們在內(nèi)存映射和共享內(nèi)存方面的優(yōu)勢和適用場景,同時,文章還會分享一些使用mmap和shm的技巧和經(jīng)驗,以幫助讀者優(yōu)化并提高程序性能,使你能夠在實際項目中更好地利用這些技術(shù)來加速數(shù)據(jù)共享和多線程應(yīng)用2023-10-10