CS106L: Lec11 Special Member Functions
There are six special member functions, These functions are generated only when they’re called:
- Default constructor: Takes no parameters and creates a new object.
- Destructor: Called when an object goes out of scope.
- Copy constructor: Creates a new object as a member-wise copy of another.
- Copy assignment operator: Assigns an already existing object to another.
- Move constructor
- Move assignment operator
We don’t have to write out any of these. They all have default versions that are generated automatically.
By default, the copy constructor will create copies of each member variable. This is member-wise copying. Many times, we will want to create a copy that does more than just copies the member variables.
Deep copy: An object that is a complete, independent copy of the original.
delete are key words in c++.
Declaring any user-deﬁned constructor will make the default disappear. If we need to use the default special member function we need add
=default is only used for special member functions of the class that have no default parameters. Can be defined either inside the class body (inline) or outside the class body (out-of-line).
Setting a special member function to
=delete removes its functionality. Thus we can selectively allow functionality of special member functions.
=delete can not be used at
Move constructors and move assignment operators will perform “memberwise moves”.
Deﬁning a move assignment operator prevents generation of a move copy constructor, and vice versa.
Move constructors and operators are only generated if:
- No copy operations are declared.
- No move operations are declared.
- No destructor is declared.
If we want to explicitly support move operations, we can set the operators to
When the item on the right of the
= is an r-value we should use move assignment.
r-values are always about to die, so we can steal their resources.
Different with l-value reference, we use
&& to present r-value reference.
std::move function mainly converts a l-value into a r-value reference.
std::move to force the use of other types’ move assignments and constructors.
After a variable is moved via
std::move, it should never be used until it is reassigned to a new variable.
std::move outside of class definitions, never use it in application code.