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
問題
由於移動操作ö n原始類型只是一個副本,我可以假設
v1
將保持不變或者即使使用原始類型也未指定狀態?我假設原始類型沒有移動語義的原因是因爲複製一樣快或甚至更快,這是正確的嗎?
「有效但未指定的狀態」規則僅適用於標準庫類型([lib.types.movedfrom])。 「移動」原始類型由核心語言規則控制,對於這種類型移動是複製。 – 2015-06-15 23:44:34