我是編程新手,我試圖編寫一個從列表中獲取最短字符串的函數,但每次運行它時,Visual Studio都會顯示錯誤「拋出的異常:讀取訪問衝突」。錯誤在哪裏?C++爲什麼我的程序拋出異常?
#include <iostream>
#include <string>
using namespace std;
const string &shortest_string(initializer_list<string> strings) {
string *shortest_one = nullptr;
for (string string : strings) {
if (shortest_one == nullptr) shortest_one = &string;
else {
if (string.size() < shortest_one->size()) shortest_one = &string;
}
}
return *shortest_one;
}
int main() {
cout << shortest_string({ "hello" , "my", "name", "is", "dan" }) << endl;
return 0;
}
因爲'string string:...'創建了一個臨時變量,它存在於循環的一個循環中並在下一個循環中被破壞。並且你正在使用它的指針(指向釋放內存) – myaut
'if(shortest_one = nullptr)' - 你認爲這樣做了什麼? –
所以,現在你已經問了第二個不同的問題,我們什麼時候才能看到真正的代碼展品的行爲? – IInspectable