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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 37: Move Semantics | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

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.

4 points
  • Understanding l‑values vs. r‑values
  • Implementing move constructors and move‑assignment operator
  • std::move and std::forward utilities
  • When move semantics provide benefits

Move Semantics

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.


Example: Implementing a movable Buffer class

class 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;
}

Perfect forwarding

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 noexcept to allow containers like std::vector to move elements during reallocation.


<Alert type="info">If a class can be safely copied with the default behaviour, = default is preferable to writing boilerplate.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 36: File I/O StreamsContinue to lesson 38Lesson 38: Threads (std::thread)Back to C++ Course curriculum