2014-10-10 54 views
2
using std::map; 
    map<string, int> mapStrToInt; 
    { 
      map<string, int> mapStrToInt2; 
      mapStrToInt2[ "h1" ] = 100; 
      mapStrToInt2[ "h2" ] = 200; 
      mapStrToInt2[ "h3" ] = 300; 
      mapStrToInt2[ "h4" ] = 400; 

      mapStrToInt.insert(mapStrToInt2.begin(), mapStrToInt2.end()); 
      mapStrToInt.swap(mapStrToInt2); // is this code safe? 
    } 
    // at this point mapStrToInt2 has been destroyed. 

問題>我已經測試此代碼VS2013和mapStrToInt內容已被交換與的mapStrToInt2。但是,我仍然想確認交換臨時對象的內容是否安全&合法。使用臨時地圖交換地圖實例是否安全?

謝謝

+0

代碼是完全合法的.. – Nim 2014-10-10 15:28:08

回答

4

它既安全又合法。當交換兩個容器的內容時​​,內容的所有權從一個變爲另一個。因此mapStrToInt的舊內容歸臨時所有,在退出範圍時不再存在,臨時的舊內容由mapStrToInt接管。

相關問題