Before C++11, returning a large container (like an array or vector) from a function required making an expensive Deep Copy ($O(N)$ time). Move Semantics revolutionized C++ by enabling the transfer of resource ownership from temporary objects in $O(1)$ constant time.
#include <iostream>
#include <utility>
class Buffer {
private:
int* data;
int size;
public:
Buffer(int s) : size(s), data(new int[s]{}) {}
// Move Constructor (noexcept is best practice for STL vector realloc)
Buffer(Buffer&& other) noexcept : data(other.data), size(other.size) {
// STEAL the pointer!
other.data = nullptr;
other.size = 0;
std::cout << "Move Constructor executed: O(1) pointer swap!\n";
}
~Buffer() {
delete[] data;
}
};
int main() {
Buffer b1(1000000); // 1 million integers
Buffer b2 = std::move(b1); // Blazing fast! Zero integers copied!
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Copy constructors and the Rule of Five.
How std::unique_ptr relies entirely on move semantics.
Move semantics inside std::vector reallocation.