Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 31 of 45 · C++

Lesson 37: Move Semantics

Duration: 13 min

Move Semantics\n\nMove 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.\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.

Previous: Lesson 36: File I/O StreamsNext: Lesson 38: Threads (std::thread)