Lesson 31 of 45 · C++
Lesson 37: Move Semantics
Duration: 13 min
Lesson 31 of 45 · C++
Duration: 13 min
T&&) and the std::move utility.\n\n---\n\n## Example: Implementing a movable Buffer class\ncpp\nclass Buffer {\n std::size_t size_;\n char* data_;\npublic:\n explicit Buffer(std::size_t n) : size_(n), data_(new char[n]) {\n std::fill(data_, data_ + size_, 0);\n }\n // Move constructor\n Buffer(Buffer&& other) noexcept : size_(other.size_), data_(other.data_) {\n other.size_ = 0;\n other.data_ = nullptr;\n }\n // Move assignment\n Buffer& operator=(Buffer&& other) noexcept {\n if (this != &other) {\n delete[] data_;\n size_ = other.size_;\n data_ = other.data_;\n other.size_ = 0;\n other.data_ = nullptr;\n }\n return *this;\n }\n ~Buffer() { delete[] data_; }\n std::size_t size() const { return size_; }\n};\n\nint main() {\n Buffer b1(1024);\n Buffer b2 = std::move(b1); // b1 is now empty, b2 owns the memory\n std::cout << \"b2 size = \" << b2.size() << '\\n';\n return 0;\n}\n\n\n## Perfect forwarding\ncpp\ntemplate <typename T, typename... Args>\nstd::unique_ptr<T> make_unique_forward(Args&&... args) {\n return std::unique_ptr<T>(new T(std::forward<Args>(args)...));\n}\n\n\n> Tip: Declare move constructors and move assignment operators as noexcept to allow containers like std::vector to move elements during reallocation.\n\n---\n\n<Alert type="info">If a class can be safely copied with the default behaviour, = default is preferable to writing boilerplate.