Use Move Constructor and Move Assignment Operator - C++ Class

C++ examples for Class:Constructor

Description

Use Move Constructor and Move Assignment Operator

Demo Code

#include <cinttypes>
#include <cstring>
#include <iostream>

using namespace std;

class Car//from ww w.jav  a  2 s .  co m
{
private:
    char* m_Name{};
    int m_NumberOfWheels{};

public:
    Car() = default;

    Car(const char* name, int numberOfWheels)
        : m_NumberOfWheels{ numberOfWheels }
    {
        const int length = strlen(name) + 1; // Add space for null terminator
        m_Name = new char[length]{};
        strcpy(m_Name, name);
    }
    ~Car()
    {
        if (m_Name != nullptr)
        {
            delete m_Name;
            m_Name = nullptr;
        }
    }

    Car(const Car& other)
    {
        const int length = strlen(other.m_Name) + 1; // Add space for null terminator
        m_Name = new char[length]{};
        strcpy(m_Name, other.m_Name);

        m_NumberOfWheels = other.m_NumberOfWheels;
    }

    Car& operator=(const Car& other)
    {
        if (m_Name != nullptr)
        {
            delete m_Name;
        }

        const int length = strlen(other.m_Name) + 1; // Add space for null terminator
        m_Name = new char[length]{};
        strcpy(m_Name, other.m_Name);

        m_NumberOfWheels = other.m_NumberOfWheels;

        return *this;
    }

    Car(Car&& other)
    {
        m_Name = other.m_Name;
        other.m_Name = nullptr;

        m_NumberOfWheels = other.m_NumberOfWheels;
    }

    Car& operator=(Car&& other)
    {
        if (m_Name != nullptr)
        {
            delete m_Name;
        }
        m_Name = other.m_Name;
        other.m_Name = nullptr;

        m_NumberOfWheels = other.m_NumberOfWheels;

        return *this;
    }

    char* GetName()
    {
        return m_Name;
    }

    int GetNumberOfWheels()
    {
        return m_NumberOfWheels;
    }
};

int main(int argc, char* argv[])
{
    Car myAssignedCar;

    {
        Car myCar{ "myCar", 4 };
        cout << "Car name: " << myCar.GetName() << endl;

        myAssignedCar = move(myCar);
        //cout << "Car name: " << myCar.GetName() << endl;
        cout << "Car name: " << myAssignedCar.GetName() << endl;
    }

    cout << "Car name: " << myAssignedCar.GetName() << endl;

    return 0;
}

Result


Related Tutorials