Junior — Middle
Can you explain how the semantics of object movement are implemented in C++?
sobes.tech AI
Answer from AI
Move semantics in C++ allows efficient transfer of resources (e.g., memory) from one object to another without copying. This is implemented using rvalue references and special move constructors and operators.
Key points:
- The move constructor takes an rvalue reference (
Type&&) and 'steals' resources from a temporary object. - After moving, the original object remains in a valid but unspecified state (usually with null or empty resources).
Example:
class Buffer {
char* data;
size_t size;
public:
Buffer(size_t s) : size(s), data(new char[s]) {}
~Buffer() { delete[] data; }
// Move constructor
Buffer(Buffer&& other) noexcept : data(other.data), size(other.size) {
other.data = nullptr;
other.size = 0;
}
// Move assignment operator
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
delete[] data;
data = other.data;
size = other.size;
other.data = nullptr;
other.size = 0;
}
return *this;
}
// Delete copy constructor and copy assignment for clarity
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
};
Thus, move semantics help avoid costly copying of large resources, improving performance.