Ownership
Move Semantics
Moving transfers ownership from one object to another.
Move Semantics
move_semantics.cpp
#include <iostream>
#include <memory>
#include <string>
int main() {
std::string name = ;
std::unique_ptr<std::string> original = std::make_unique<std::string>(name);
std::unique_ptr<std::string> moved = std::move(original);
std::cout << "originalEmpty=" << (original == nullptr) << std::endl;
std::cout << "movedValue=" << *moved << std::endl;
return 0;
}
#include <iostream>
#include <memory>
#include <string>
int main() {
std::string name = ;
std::unique_ptr<std::string> original = std::make_unique<std::string>(name);
std::unique_ptr<std::string> moved = std::move(original);
std::cout << "originalEmpty=" << (original == nullptr) << std::endl;
std::cout << "movedValue=" << *moved << std::endl;
return 0;
}
#include <iostream>
#include <memory>
#include <string>
int main() {
std::string name = ;
std::unique_ptr<std::string> original = std::make_unique<std::string>(name);
std::unique_ptr<std::string> moved = std::move(original);
std::cout << "originalEmpty=" << (original == nullptr) << std::endl;
std::cout << "movedValue=" << *moved << std::endl;
return 0;
}
move
`std::move` allows movable objects such as `std::unique_ptr` to transfer ownership.