2013-03-09 51 views
2

如何讓下面的代碼只調用移動構造函數一次如何僅對移動構造函數進行一次調用?

輸出

MC 
MC 

CODE

#include <vector> 
#include <map> 
#include <memory> 
#include <iostream> 

struct Bar 
{ 
     Bar() { } 
     Bar(Bar&& rhs) 
     { 
       std::cerr << "MC\n"; 

       for(auto& p : rhs.m_v) 
       { 
         std::cerr << "inside loop\n"; 
         m_v.push_back(move(p)); 
       } 
     } 
     std::vector< std::unique_ptr<Bar>> m_v; 
}; 

int main() 
{ 
     Bar b; 

     std::map<int,Bar> m; 
     m.insert(std::make_pair(1, std::move(b))); 
} 

編輯

看起來emplace是正確的答案 - 但不幸的是,它不是在GCC 4.7.2然而......有沒有我可以將其別名insert,然後在正確實施時將其刪除?

+1

'地圖:: emplace'似乎與[GCC 4.8.0(HTTP工作:// liveworkspace .org/code/1FWK1L $ 26),如果你不介意安裝非發佈版本。 – Praetorian 2013-03-09 18:05:52

+0

@Praetorian +1 ty爲信息 – kfmfe04 2013-03-09 18:08:04

回答

4

基本上使用emplace代替insert

m.emplace(1, std::move(b)); 
+2

ack - 我使用的是gcc 4.7.2 - 有沒有解決方法,或者我可以在預期其實施方面做些什麼? – kfmfe04 2013-03-09 17:46:20

+0

嗯...我想我得到一個'sandbox.cpp:27:4:錯誤:'class std :: map '沒有名爲'emplace''的成員 - 可能是我的安裝出錯 – kfmfe04 2013-03-09 17:47:47

+0

@ kfmfe04 [這不只是你](http://ideone.com/rWbDyF) – David 2013-03-09 17:50:27

相關問題