codice di esempio:Spostare semantica e di tipo primitivo
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);
}
uscita:
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
Domande
Dal operazioni di spostamento o n tipi primitivi è solo una copia, posso supporre che
v1
rimarrà invariato o lo stato non è specificato anche con tipi primitivi?Sto assumendo il motivo per cui i tipi primitivi non hanno la semantica del movimento è perché la copia è altrettanto veloce o anche più veloce, è corretto?
La regola "stato valido ma non specificato" si applica solo ai tipi di libreria standard ([lib.types.movedfrom]). I tipi primitivi "commoventi" sono controllati dalle regole linguistiche di base e, per tali tipi, una mossa è una copia. –