Trước C++11, truyền object lớn (vector, string) vào hàm luôn copy → tốn kém. Move semantics cho phép "chuyển nhượng" tài nguyên thay vì copy.
- lvalue: object có địa chỉ xác định (có thể lấy
&). - rvalue: giá trị tạm thời, không có địa chỉ bền vững (kết quả biểu thức, literal).
T&&(rvalue reference): bind vào temporary, cho phép "cướp" tài nguyên.
cpp
std::vector<int> a = {1, 2, 3};
std::vector<int> b = std::move(a); // a rỗng sau move, b có data
// std::move: cast sang rvalue reference — không move gì cả, chỉ castKết quả: push_back với rvalue không copy nữa — cải thiện hiệu năng đáng kể với object lớn.
Return value từ hàm (RVO/NRVO) cũng được tối ưu tương tự.
Before C++11, passing large objects (vectors, strings) always copied them — expensive. Move semantics allow transferring resources instead of copying.
- lvalue: object with a stable address (addressable with
&). - rvalue: temporary value with no persistent address (expression result, literal).
T&&(rvalue reference): binds to temporaries, enabling resource "theft".
cpp
std::vector<int> a = {1, 2, 3};
std::vector<int> b = std::move(a); // a is empty after; b holds the data
// std::move: cast to rvalue reference — does not move anything by itselfResult: push_back with an rvalue no longer copies — significant performance gain for large objects.
Return values (RVO/NRVO) are similarly optimised.