CodeTheRobot

C++ Intermediate · Lesson 04 of 27

Move semantics: move constructor, move assignment and std::move

Transferring resources instead of copying, and the rule of five.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain move semantics: move constructor, move assignment and std::move in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

Copying duplicates a resource; moving transfers it from an object that is about to be discarded. A move constructor (T(T&&)) and move assignment (T& operator=(T&&)) steal the buffer and leave the source valid but empty. std::move does not move anything: it only marks an object as movable.

If a class manages a resource, define or delete all five special functions (destructor, copy constructor, copy assignment, move constructor, move assignment). Mark moves noexcept so containers use them. Do not use a moved-from object except to assign or destroy it.

Guided lesson

Work through these steps

  1. 1.

    Read the move semantics: move constructor, move assignment and std::move example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

class Frame {
// A type that owns a growable buffer.
public:
// Public interface.
  explicit Frame(std::size_t n) : data_(n) {}
// Allocate n values.
  Frame(const Frame&) = default;
// Copy constructor: duplicate the buffer.
  Frame& operator=(const Frame&) = default;
// Copy assignment: overwrite with a duplicate.
  Frame(Frame&& other) noexcept : data_{std::move(other.data_)} {}
// Move constructor: steal the buffer; noexcept lets vectors use it.
  Frame& operator=(Frame&& other) noexcept { data_ = std::move(other.data_); return *this; }
// Move assignment: steal the buffer from other.
  ~Frame() = default;
// The vector member frees itself.
private:
// Hidden data.
  std::vector<double> data_;
// The owned resource.
};
// End of the class.
Frame a{1000};
// Create a frame with 1000 values.
Frame b = std::move(a);
// Move: b takes the buffer; a is valid but empty.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Values in memory

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

motor speed030x1070x1410x1890x1c40x2060x2420x2880x2c*p += 10VALUES IN MEMORY

Demo for Move semantics: move constructor, move assignment and std::move. Expected result: 0 1000

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <iostream>
#include <utility>
#include <vector>

class Frame {
 public:
  explicit Frame(std::size_t n) : data_(n) {}
  Frame(const Frame&) = default;
  Frame& operator=(const Frame&) = default;
  // TODO: write the move constructor and move assignment: steal data_ with std::move, both noexcept
  std::size_t size() const { return data_.size(); }

 private:
  std::vector<double> data_;
};

int main() {
  Frame a{1000};
  Frame b = std::move(a);
  std::cout << a.size() << ' ' << b.size() << '\n';
  return 0;
}

Expected output

0 1000
Stuck? Show the full solution (try it yourself first)
#include <iostream>
#include <utility>
#include <vector>

class Frame {
 public:
  explicit Frame(std::size_t n) : data_(n) {}
  Frame(const Frame&) = default;
  Frame& operator=(const Frame&) = default;
  Frame(Frame&& other) noexcept : data_{std::move(other.data_)} {}
  Frame& operator=(Frame&& other) noexcept {
    data_ = std::move(other.data_);
    return *this;
  }
  std::size_t size() const { return data_.size(); }

 private:
  std::vector<double> data_;
};

int main() {
  Frame a{1000};
  Frame b = std::move(a);
  std::cout << a.size() << ' ' << b.size() << '\n';
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Create a FrameBuffer that logs 'copy' and 'move' from its special functions. Return one from a function, put it in a vector, and compare the log with and without std::move at the call site.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.