Advanced Classes and Objects Part III

Part III

Using swap

When using moveFrom, if a new data member is added, both swap and moveFrom have to be modified. To avoid that, one can write the move constructor and move assignment operator with a default constructor and the swap function.
class Bank
{
    private: 
        Bank() = default;
}
Now cleanup() and moveFrom() can be removed. The destructor handles the code from cleanup. The code is as follows:
Bank::Bank(Bank&& src) noexcept : Bank()
{ 
    swap(*this,src); //Default constructor creates *this.
}

Bank& Bank::operator=(Bank&& rhs) noexcept
{
    Bank temp(std::move(rhs)) //Need std::move because rhs is named
    swap(*this,temp);
    return *this;
}

Implementing swap with move semantics

Using move semantics improves the performance of swap as seen below:
void swap(T &a , T&b)
{
    T temp(std::move(a));
    a = std::move(b);
    b = std::move(temp);
}

Rule of zero

In, Modern C++ the rule of zero is preferred. This states that the class design obviates the need for the five special member functions, by avoiding legacy style memory allocation and using STL containers. For example, use vector<CheckingAccount> instead of CheckingAccount*.

Static methods

Static methods are related to the class itself and do not operate on any members of the class. It can access private and protected static members of the class. If a reference to an object is passed in, they can also access private and protected non-static data members on objects of the same type.

Method overloading

You can overload methods, as long as the number and/or types of parameters differ.

Inline methods

One can recommend to the compiler that a method or function should inline it. It is just a hint, not a guarantee that the compiler will honor it. inline methods' definitions should be placed in a header file along with their prototypes.

Static data members

static data member is associated with a class instead of a particular object. For example, the bank could maintain the number of checking accounts it has with a static data member.

References:

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

Comments

Popular posts from this blog

QTreeView and QTableView dynamic changes

C++ strings and string_view