2013-06-12 57 views
2

假設我有以下代碼(C++/QT):一個鏈接到一個鏈接在C++ 11 foreach循環

QHash<QString, AppInfo*> links; 
QList<AppInfo> apps = m_apps.values(); 
for (const AppInfo &app : apps) { 
    // Doing something with #app variable... 
    links.insert(app.other._appFile, &app); 
} 

m_appsQHash<QString, AppInfo>,並app.other._appFile是給文件的完整路徑。

這裏提出的問題是:倒數第二行中的構造&app是否正確?我需要一個指向AppInfo對象的非常量指針以稍後修改它。是否&app直接鏈接到const AppInfo&AppInfo對象?如果我嘗試修改獲得的AppInfo*對象,是不是應用程序崩潰?謝謝。

對不起,英語不是我的母語,我不能完美地制定問題標題。請做,而不是我。

+0

如果你需要一個非const'了AppInfo *',那麼你是顯示的代碼不應該編譯。它是否編譯? – juanchopanza

+0

不會簡單地在'const AppInfo&app:apps'中刪除const嗎? –

+0

@juanchopanza我現在沒有C++編譯器。 –

回答

2

linksQHash<QString, AppInfo*>,不QHash<QString, const AppInfo*>,因此通過

links.insert(app.other._appFile, &app); 

您正在發起從const AppInfo*AppInfo*的隱式轉換,這將導致一個編譯錯誤,而不是運行時間錯誤(崩潰)。一個顯而易見的解決方案是穿越地圖,而常量

for (AppInfo &app : apps) 
{ 

}