~/okanakyuz
← all posts

Copy and Move Constructors

How copy and move constructors work in C++, with an example class that owns a pointer, plus notes on std::move, noexcept and copy elision.

2 March 2020updated 25 November 20262 min read

In the life of a C++ programmer, there are two interesting constructors you should know well. One of them is for copying an object and the other one is for moving its data.

The copy constructor receives a reference to another object of the same class. The parameter should be const, because copying must not modify the source object. The structure of the method is:

MyClass(const MyClass & ref);

The other one is the move constructor, which receives an rvalue reference (&&). The structure is:

MyClass(MyClass && ref);

The move constructor runs when a new object is created from an rvalue, like a temporary object or something you passed through std::move. Instead of copying the data, it steals the resources (memory, file handles, …) of the source object.

In the following code, you can find an example:

#include <iostream>

class MyClass {
private:
    int *p_int;
public:

    //Constructor
    MyClass(){
        std::cout << "MyClass()" << std::endl;
        p_int = new int;
        *p_int = 0;
    }

    //Set value on constructor
    MyClass(int x){
        std::cout << "MyClass(" << x << ")" << std::endl;
        p_int = new int;
        *p_int = x;
    }

    int getValue() const{
        return *p_int;
    }

    void setValue(int x){
        *p_int = x;
    }

    //Copy Constructor
    MyClass(const MyClass & ref){
        std::cout << "MyClass(const MyClass & ref)" << std::endl;
        p_int = new int;
        *p_int = ref.getValue();
    }

    //Move constructor
    MyClass(MyClass && ref) noexcept {
        std::cout << "MyClass(MyClass && ref)" << std::endl;
        p_int = ref.p_int;
        //after moving the value you have
        //to set the source pointer to null
        ref.p_int = nullptr;
    }

    void getStatus(){
        std::cout << "Value = " << this->getValue() << std::endl;
    }

    ~MyClass(){
        std::cout << "~MyClass()" << std::endl;
        delete p_int;
    }

};

MyClass adder(const MyClass &a, const MyClass &b){
    MyClass temp;
    temp.setValue(a.getValue() + b.getValue());
    return temp;
}

int main(){
    MyClass x{5}, y{2};
    x.setValue(adder(x,y).getValue());
}

The move constructor has to set the source pointer to nullptr. Otherwise, when the old object is destroyed, its destructor deletes the same memory and the new object is left with a dangling pointer. Deleting a nullptr is fine, so the destructor doesn’t need a check. Just don’t call getValue() on a moved-from object, because it dereferences a null pointer.

I marked the move constructor noexcept. This matters more than it looks: containers like std::vector only move elements when they grow if the move constructor is noexcept, otherwise they copy them to keep the strong exception guarantee.

Don’t be surprised if you don’t see the move constructor in the output when you run this. return temp; is a candidate for named return value optimization (NRVO), and compilers usually construct temp directly in the caller’s memory, so neither copy nor move is called. Since C++17, returning a temporary (a prvalue like return MyClass{};) is guaranteed to skip the copy/move. For a named local like temp it is still only allowed, not guaranteed, and if the compiler doesn’t do it, the move constructor is used.

To force the move constructor to run, use std::move. It is in the <utility> header. std::move doesn’t move anything by itself, it just casts the object to an rvalue reference so the move constructor is chosen:

MyClass a{5};
MyClass b{std::move(a)}; // MyClass(MyClass && ref)

One more thing: this class doesn’t have a copy assignment or a move assignment operator. Because it declares a move constructor, the compiler defines the copy assignment as deleted, so x = y; doesn’t even compile. If you need assignment, write both operators yourself (the “rule of five”). Never rely on a compiler generated assignment for a class like this, because it would just copy the pointer and two objects would delete the same memory.