溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C++錯(cuò)誤使用迭代器超出引用范圍問題如何解決

發(fā)布時(shí)間:2023-03-25 14:40:34 來源:億速云 閱讀:106 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“C++錯(cuò)誤使用迭代器超出引用范圍問題如何解決”,在日常操作中,相信很多人在C++錯(cuò)誤使用迭代器超出引用范圍問題如何解決問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”C++錯(cuò)誤使用迭代器超出引用范圍問題如何解決”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

相關(guān)錯(cuò)誤

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)

錯(cuò)誤截圖

C++錯(cuò)誤使用迭代器超出引用范圍問題如何解決

C++錯(cuò)誤使用迭代器超出引用范圍問題如何解決

錯(cuò)誤代碼塊

C++錯(cuò)誤使用迭代器超出引用范圍問題如何解決

錯(cuò)誤原因

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

end()方法將迭代器返回到最后一個(gè)元素之后,指向字符串最后一個(gè)字符下一個(gè)位置。由于它并不指向?qū)嶋H的字符,因此不能對(duì)該迭代器進(jìn)行解引用操作。

如果想訪問最后一個(gè)元素,應(yīng)該使用

  • string.end() - 1 :注意,該語(yǔ)句僅適用于非空字符串,否則將會(huì)越界訪問

  • 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 診斷改進(jìn)。 當(dāng) IDL 檢查在字符串機(jī)制中失誤時(shí),它現(xiàn)在會(huì)報(bào)告導(dǎo)致失誤的特定行為。 例如,現(xiàn)在會(huì)收到“無法取消引用字符串迭代器,因?yàn)槠湟殉龇秶ɡ缒┪驳鳎?,而不是“字符串迭代器不可取消引用”?/p>

在更新日志中已經(jīng)告訴了我們錯(cuò)誤的原因了

C++錯(cuò)誤使用迭代器超出引用范圍問題如何解決

到此,關(guān)于“C++錯(cuò)誤使用迭代器超出引用范圍問題如何解決”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI