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 更新日志
- Minor
basic_string _ITERATOR_DEBUG_LEVEL != 0diagnostics 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++迭代器超出引用范圍內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
cin.get()和cin.getline()之間的區(qū)別
以下是對cin.get()和cin.getline()的區(qū)別進行了詳細的分析介紹,需要的朋友可以過來參考下,希望對大家有所幫助2013-09-09

