Move semantics let an object transfer ownership of internal resources to another object instead of duplicating them. When the source is an rvalue (temporary or result of std::move), the compiler picks a move constructor instead of copying, stealing resources and leaving the source empty.
Use move semantics to avoid expensive deep copies of temporary objects and to enable efficient resource ownership transfer.
This example shows how move semantics transfer resource ownership instead of copying.
// compile: g++ -o move move.cpp // run: ./move // description: move semantics transfer ownership without copying #include <iostream> #include <memory> class Buffer { public: int* data; size_t size; Buffer(size_t n) : size(n) { data = new int[n]; std::cout << "Buffer allocated\n"; } ~Buffer() { delete[] data; std::cout << "Buffer freed\n"; } Buffer(Buffer&& other) noexcept : data(other.data), size(other.size) { other.data = nullptr; std::cout << "Buffer moved\n"; } }; int main() { Buffer b1(1000); Buffer b2 = std::move(b1); // b2 steals b1's buffer; b1.data is now null return 0; }