Chapter 11. Classes: Special Member Functions and Move Semantics
In Chapter 10, you wrote your own class and discovered that the compiler can generate special member functions for you, such as constructors and destructors. This chapter will show you the other special member functions, when they are used, and why they matter.
This chapter is a deep dive to explain some important ideas, including move semantics: a way to make your code more efficient by transferring resources.
As it stands, your Stock class works well enough, but taking time to understand what is happening will give you a solid C++ foundation.
You will also learn about how a std::string works in detail, seeing what happens in each special member function.
This will show you why C++ provides various special member functions for classes and what they do.
Copying Objects
In the previous chapter, in Example 10-4, you made a vector of stocks, as shown in Example 11-1.
Example 11-1. A vector of stocks from an initializer list
#include<vector>#include"stock.h"intmain(){usingnamespacestock_prices;std::vectorstocks{Stock{"Coffee",4.8,0.0113},Stock{"Tea",171.68,0.023},Stock{"Sugar",17.91,0.05}};}
This code calls a constructor three times but calls six destructors.
The initializer list contains three objects that are copied to the std::vector.
The copying happens via a special member function called a copy constructor, designed to make a copy of an existing object.
Figure 11-1 shows how you end ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access