I'm trying to better understand how moving works in C++. How does the compiler know when to move and when not to move?
#include <iostream>
template <typename T>
struct Container {
T value;
Container (T value): value(value) {}
Container (const Container & i): value(i.value) {
std::cout << "copying" << std::endl;
}
Container (Container && i): value(std::move(i.value)) {
std::cout << "moving" << std::endl;
}
};
void increment (Container<int> n) {
std::cout << "incremented to " << ++n.value << std::endl;
}
int main () {
Container<int> n (5);
increment(std::move(n));
std::cout << n.value << std::endl;
}
This example prints
moving
incremented to 6
5
So I'd expect the int to have been moved, but then I shouldn't be able to still use it afterwards (and get the original value).
OK, so maybe the int was copied because value(std::move(i.value)) copied it in the move constructor. But I still don't understand why Container<int> n is still around after it's definitely been moved.
Aucun commentaire:
Enregistrer un commentaire