Advanced Classes and Objects Part II

Part II

Continuing from Part I, here are the implementations of cleanupmoveFrom, the move constructor and the move assignment operator.
void Bank::cleanup() noexcept
{
    delete[] mCheckingAccounts;
    mCheckingAccounts = nullptr;
    mName = "";
    mNumAccounts = 0;
}

void Bank::moveFrom(Bank &src) noexcept
{
    //Shallow copy first. Move objects.
    mNumAccounts = src.mNumAccounts;
    mCheckingAccounts = src.mCheckingAccounts;
    mName = std::move(src.mName);

    //Ownership has moved, reset the source object
    src.mName = "";
    src.mNumAccounts = 0;
    src.mCheckingAccounts = nullptr;
}

//Move constructor
Bank::Bank(Bank&& src) noexcept
{
    moveFrom(src);
}

//Move assignment operator
Bank&::Bank::operator=(Bank && rhs) noexcept
{
    if(this == &rhs)
    {
        return *this;
    }

    cleanup();
    moveFrom(rhs);

    return *this;
}

Rule of Five

The rule of five states that if one dynamically allocates memory in the class, then one should implement a destructor, copy constructor, move constructor, copy assignment operator, and move assignment operator.

References:

Gregoire, M. (2018). Professional C++. Indiana, IN: John Wiley & Sons.

Comments

Popular posts from this blog

C++ strings and string_view

QTreeView and QTableView dynamic changes