C++ Code reusability between copy constructor and assignment operator (=) [duplicate]

In OOP: For efficient code maintenance, what is the standard best practice to "link" deep copy constructors, and deep copy through assignment operator (=), so that they perform consistently?

I want to be able to edit the copy logic in one place (say, the copy constructor), and for it to be changed also for the assignment operator.

My take would be the following:

class MyClass
{
private:
    int* _data;

    MyClass& _deep_copy(const MyClass& source)
    {   
        delete _data;
        _data = new int;
        *_data = *source._data;
        return *this; // assuming &source != this
    }

public:
    MyClass() : _data{nullptr} {}

    MyClass(const int data)
    {
        _data = new int;
        *_data = data;
    }

    MyClass(const MyClass& source)
    {
        _data = nullptr;
        _deep_copy(source);
    }
    MyClass& operator=(const MyClass& source)
    {
        return _deep_copy(source);
    }
};

Maybe there’s a way to use some sort of "delegation"?

Thank you!

Source: Windows Questions C++

LEAVE A COMMENT