Lesson 37 of 45
C++Lesson 37: Move Semantics
13 min
Course progress82%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 37 of 45
C++13 min
Keep these ideas in mind as you work through the lesson.
Move semantics, introduced in C++11, allow the efficient transfer of resources from one object to another without costly copying. This is expressed via r‑value references (T&&) and the std::move utility.
Buffer classclass Buffer {
std::size_t size_;
char* data_;
public:
explicit Buffer(std::size_t n) : size_(n), data_(new char[n]) {
std::fill(data_, data_ + size_, 0);
}
// Move constructor
Buffer(Buffer&& other) noexcept : size_(other.size_), data_(other.data_) {
other.size_ = 0;
other.data_ = nullptr;
}
// Move assignment
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
delete[] data_;
size_ = other.size_;
data_ = other.data_;
other.size_ = 0;
other.data_ = nullptr;
}
return *this;
}
~Buffer() { delete[] data_; }
std::size_t size() const { return size_; }
};
int main() {
Buffer b1(1024);
Buffer b2 = std::move(b1); // b1 is now empty, b2 owns the memory
std::cout << \"b2 size = \" << b2.size() << '\
';
return 0;
}
template <typename T, typename... Args>
std::unique_ptr<T> make_unique_forward(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
Tip: Declare move constructors and move assignment operators as
noexceptto allow containers likestd::vectorto move elements during reallocation.
<Alert type="info">If a class can be safely copied with the default behaviour, = default is preferable to writing boilerplate.