2012-04-03 76 views
9

示例代碼移動語義和原始類型

int main() 
{ 
    std::vector<int> v1{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 
    std::cout << "Printing v1" << std::endl; 
    print(v1); 
    std::vector<int> v2(std::make_move_iterator(v1.begin()), 
         std::make_move_iterator(v1.end())); 
    std::cout << "Printing v1" << std::endl; 
    print(v1); 
    std::cout << "Printing v2" << std::endl; 
    print(v2); 

    std::vector<std::string> v3{"some", "stuff", "to", 
         "put", "in", "the", "strings"}; 
    std::cout << "Printing v3" << std::endl; 
    print(v3); 
    std::vector<std::string> v4(std::make_move_iterator(v3.begin()), 
           std::make_move_iterator(v3.end())); 
    std::cout << "Printing v3" << std::endl; 
    print(v3); 
    std::cout << "Printing v4" << std::endl; 
    print(v4); 
} 

輸出

Printing v1 
1 2 3 4 5 6 7 8 9 10 
Printing v1 
1 2 3 4 5 6 7 8 9 10 
Printing v2 
1 2 3 4 5 6 7 8 9 10 
Printing v3 
some stuff to put in the strings 
Printing v3 

Printing v4 
some stuff to put in the strings 

問題

  1. 由於移動操作ö n原始類型只是一個副本,我可以假設v1將保持不變或者即使使用原始類型也未指定狀態?

  2. 我假設原始類型沒有移動語義的原因是因爲複製一樣快或甚至更快,這是正確的嗎?

回答

14
  1. 沒有,如果你希望能夠承擔起這個你應該複製,無法移動。

  2. 移動使源對象以有效但未指定的狀態離開。原始類型展現移動語義。源對象保持不變的事實表明,複製是實現移動的最快方式。

+1

「有效但未指定的狀態」規則僅適用於標準庫類型([lib.types.movedfrom])。 「移動」原始類型由核心語言規則控制,對於這種類型移動是複製。 – 2015-06-15 23:44:34