Adding a Move Constructor to class - C++ Class

C++ examples for Class:Constructor

Description

Adding a Move Constructor to class

Demo Code

#include <iostream>

using namespace std;

class MyClass/*from   w  w  w.j  a va 2  s. com*/
{
private:
    static int s_Counter;

    int* intValue{ &s_Counter };

public:
    MyClass()
    {
        ++(*intValue);
        cout << "Constructing: " << GetValue() << endl;
    }
    ~MyClass()
    {
        if (intValue)
        {
            --(*intValue);
            intValue = nullptr;

            cout << "Destructing: " << s_Counter << endl;
        }
        else
        {
            cout << "Destroying a moved-from instance" << endl;
        }
    }

    MyClass(const MyClass& rhs) : intValue{ rhs.intValue }
    {
        ++(*intValue);
        cout << "Copying: " << GetValue() << endl;
    }

    MyClass(MyClass&& rhs)
        : intValue{ rhs.intValue }
    {
        cout << hex << showbase;
        cout << "Moving: " << &rhs << " to " << this << endl;
        cout << noshowbase << dec;
        rhs.intValue = nullptr;
    }
    int GetValue() const
    {
        return *intValue;
    }
};

int MyClass::s_Counter{ 0 };

MyClass CopyMyClass(MyClass parameter)
{
    return parameter;
}

int main()
{
    auto object1 = MyClass();

    {
        auto object2 = MyClass();
    }

    auto object3 = MyClass();
    auto object4 = CopyMyClass(object3);

    return 0;
}

Related Tutorials