Implement move semantics with rvalue references
Rvalue references (&&) bind to temporary objects (rvalues) that are about to be destroyed. They enable Move Semantics, allowing a program to 'steal' resources (like heap memory) from a temporary object instead of copying them.
Implementation:
- Move Constructor: Transfers ownership of resources from the source object to the new object and nulls out the source's pointers to prevent double-deletion.
- Move Assignment Operator: Releases current resources and transfers ownership from the source.
std::move(): A cast that converts an lvalue to an rvalue reference, enabling the use of move constructors/assignment operators.
class MyString {
public:
char* _data;
size_t _len;
// Move Constructor
MyString(MyString&& other) noexcept
: _data(other._data), _len(other._len) {
other._data = nullptr; // Prevent double-free
other._len = 0;
}
// Move Assignment
MyString& operator=(MyString&& other) noexcept {
if (this != &other) {
delete[] _data;
_data = other._data;
_len = other._len;
other._data = nullptr;
other._len = 0;
}
return *this;
}
};
MyString str1 = "example";
MyString str2 = std::move(str1); // str1's resources moved to str2