Value Categories and References
Move Reference Transfer
std::move turns a named object into an rvalue expression so ownership can be transferred.
move expression
`std::move` does not move by itself; it marks an object as movable so a move constructor or move assignment can use it.
moved-from owner
A moved-from `std::unique_ptr` becomes empty after its ownership is transferred.
Move Reference Transfer
move_reference_transfer.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
#include <memory>
int main() {
int amount = 12;
std::unique_ptr<int> source = std::make_unique<int>(amount);
std::unique_ptr<int> target = std::move(source);
std::cout << "sourceEmpty=" << (source == nullptr) << std::endl;
std::cout << "targetValue=" << *target << std::endl;
return 0;
}
#include <iostream>
#include <memory>
int main() {
int amount = 5;
std::unique_ptr<int> source = std::make_unique<int>(amount);
std::unique_ptr<int> target = std::move(source);
std::cout << "sourceEmpty=" << (source == nullptr) << std::endl;
std::cout << "targetValue=" << *target << std::endl;
return 0;
}
#include <iostream>
#include <memory>
int main() {
int amount = 30;
std::unique_ptr<int> source = std::make_unique<int>(amount);
std::unique_ptr<int> target = std::move(source);
std::cout << "sourceEmpty=" << (source == nullptr) << std::endl;
std::cout << "targetValue=" << *target << std::endl;
return 0;
}
amount ← 12, source ← (empty), target ← (empty)
4int main() {5 int amount→ 12 = 12; //@amount=5, 3067 std::unique_ptr<int> source→ (empty) = std::make_unique<int>(amount12);8 std::unique_ptr<int> target→ (empty) = std::move(source(empty));910 std::cout << "sourceEmpty=" << (source(empty) == nullptr) << std::endl;11 std::cout << "targetValue=" << *target(empty) << std::endl;12 return 0;13}outputsourceEmpty=1 targetValue=12
amount ← 5, source ← (empty), target ← (empty)
4int main() {5 int amount→ 5 = 5;67 std::unique_ptr<int> source→ (empty) = std::make_unique<int>(amount5);8 std::unique_ptr<int> target→ (empty) = std::move(source(empty));910 std::cout << "sourceEmpty=" << (source(empty) == nullptr) << std::endl;11 std::cout << "targetValue=" << *target(empty) << std::endl;12 return 0;13}outputsourceEmpty=1 targetValue=5
amount ← 30, source ← (empty), target ← (empty)
4int main() {5 int amount→ 30 = 30;67 std::unique_ptr<int> source→ (empty) = std::make_unique<int>(amount30);8 std::unique_ptr<int> target→ (empty) = std::move(source(empty));910 std::cout << "sourceEmpty=" << (source(empty) == nullptr) << std::endl;11 std::cout << "targetValue=" << *target(empty) << std::endl;12 return 0;13}outputsourceEmpty=1 targetValue=30