Junior — Middle
Explain the concept of move semantics in programming and how it differs from copying objects.
sobes.tech AI
Answer from AI
Move semantics is a mechanism in C++ (starting from C++11) that allows efficient transfer of resources from one object to another without copying.
Difference from copying:
- When copying, a new object is created with duplicated data (e.g., all fields are copied).
- When moving, resources (e.g., pointers to dynamic memory) are transferred from the source object to the new one, leaving the original object in a valid but 'empty' state.
This is especially useful for objects that own resources (memory, files, sockets) to avoid the cost of deep copying.
Example:
#include <iostream>
#include <vector>
class Buffer {
std::vector<int> data;
public:
Buffer(size_t size) : data(size) {}
// Copy constructor
Buffer(const Buffer& other) : data(other.data) {
std::cout << "Copy constructor called\n";
}
// Move constructor
Buffer(Buffer&& other) noexcept : data(std::move(other.data)) {
std::cout << "Move constructor called\n";
}
};
int main() {
Buffer buf1(100);
Buffer buf2 = buf1; // copying
Buffer buf3 = std::move(buf1); // moving
}
Output:
Copy constructor called
Move constructor called
Thus, move semantics can improve performance by avoiding unnecessary copies.