[英]Does string::replace invallidate iterators and references?
您好,我已經搜索了迭代器和類字符串的引用無效,但沒有找到結果。
我有以下代碼:
int main(){
std::string s = "const char* manipulation in C++";
auto beg = s.cbegin();
auto& r = *s.begin();
std::cout << s << std::endl;
std::cout << "*beg: " << *beg << std::endl;
std::cout << "r: " << r << std::endl;
s.replace(beg, beg + 11, "string");
std::cout << s << std::endl;
std::cout << "*beg: " << *beg << std::endl;
std::cout << "r: " << r << std::endl;
}
輸出:
const char* manipulation in C++
*beg: c
r: c
string manipulation in C++
*beg: s
r: s
看起來不錯,但我不知道它是否是未定義的行為。 謝謝!
根據此參考資料 :
與該對象有關的所有迭代器,指針和引用都可能無效。
根據[string.require] ,看起來是這樣的:
引用
basic_string
序列的元素的引用,指針和迭代器可能由於以下basic_string
對象的使用而無效:—
at
data
,front
,back
,begin
,rbegin
,end
和rend
at
調用非const成員函數 (operator[]
除外)。
我相信,如果通過replace
使字符串變小,則實現可能會決定減少容量,這將重新分配。
更新
根據C ++ 11標准,使用的replace
重載僅指定out_of_range
異常。 這意味着(?), replace
本身無法重新分配,因此不能更改其容量。 但是,我不確定庫函數是否會拋出未特別指定的異常。
在所引用的草案中, 相關的重載還提到了分配器的allocate
成員函數引發的異常 ,這暗示了重新分配的可能性。 我看不到任何將限制此異常說明的子句僅用於替換引起原始字符串擴大的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.