由於您發佈的示例代碼未編譯(typename std::string::const_iterator
應該只是std::string::const_iterator
),修復此錯誤允許代碼爲run as expected,我猜測實際代碼有點不同。
對我來說,這聽起來像一個std::string
參數被值複製的情況下,引用計數在訪問const_iterator
之前以某種方式中斷。例如,此簽名:
std::string::const_iterator return_iterator(std::string line)
//^Notice: Not passing by
// reference
按值傳遞字符串。由於COW,副本是共享的,但函數調用line.begin()
時,非const const字符串成員函數std::string::begin()
被調用,這意味着通常會創建基礎字符串的新副本。返回的非常量iterator
然後隱式轉換爲const_iterator
(完全有效的轉換)。
編輯:爲了證明我的觀點,看看那被修改以下版本的輸出由價值到line
參數傳遞給return_iterator()
:
#include <cassert>
#include <string>
#include <iostream>
std::string::const_iterator return_iterator(std::string line)
{
std::string::const_iterator beg = line.begin();
std::cout << "In return_iterator(), &(*line.begin()) is " << static_cast<const void *>(&*beg) << '\n';
/*here I'm moving this iterator and assing to it i.e.*/
beg = line.begin() + 3;
return beg;//at this point it points to a character
}
void other_fnc(const std::string& line)
{
std::string::const_iterator pos = return_iterator(line);//after this fnc returns pos points to some rubbish
std::cout << "In other_fnc(), &(*line.begin()) is " << static_cast<const void *>(&*line.begin()) << '\n';
assert(*pos == line[3]);
}
int main()
{
std::string line = "This is a test.";
other_fnc(line);
}
http://codepad.org/K9yaWqWA
斷言現在失敗了。另外請注意,*line.begin()
的地址是不同的。
請提供編譯和演示該問題最小的情況下。 – 2012-01-06 18:01:22
除非「某個位置」超出了字符串的長度(即等於或過去:: end()),否則這種情況可能不會發生。 – 2012-01-06 18:03:34