Skip to content
Justice Tech School

Copy and Move Semantics

The copy constructor duplicates an object, while move steals resources from a temporary, which is much faster for big data. The rule of zero says let the compiler generate them when you can.

Example
#include <iostream>
#include <string>
#include <vector>
#include <utility>
using namespace std;
int main() {
    vector<int> a(1000, 7);
    vector<int> b = a;
    vector<int> c = move(a);
    cout << a.size() << " " << b.size() << " " << c.size() << "\n";
    string s = "text"; string t = move(s);
    cout << t << " " << s.empty() << "\n";
}

Result

0 1000 1000
text 1

Exercise

Turn into an rvalue.

auto c = (a);

Quiz Test

What does std::move do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.