C++ rules for special member functions

C++ has several special member functions that are defined by the compiler even if not defined by the user. These special member functions are the default constructor, the copy constructor, the copy assignment operator, the move constructor, the move assignment operator, and the destructor. However, there are many rules for what is defined and in which circumstances. For instance, if no special member function is defined by the user then all of them are implicitly defined by the compiler. On the other hand, if a copy constructor or copy assignment operator is defined by the user, then the move constructor and move assignment operator are not defined by the compiler. To make it easier to comprehend all the rules, the following table describes what is defined by the compiler based on what is defined by the user.

Default constructor Copy constructor Copy operator= Move constructor Move operator= Destructor
Nothing YES YES YES YES YES YES
Any constructor NO YES YES YES YES YES
Default constructor NO YES YES YES YES YES
Copy constructor NO NO YES NO NO YES
Copy operator= YES YES NO NO NO YES
Move constructor NO DELETED DELETED NO NO YES
Move operator= YES DELETED DELETED NO NO YES
Destructor YES YES YES NO YES NO

In the table above, on the horizontal, we have the special member functions that the compiler defines and on the vertical the functions the user may define. You should read the table as follows:

YES the special member function is defined by the compiler
NO the special member function is not defined by the compiler
NO the special member function is not defined by the compiler since it is defined by the user
YES the special member function is defined by the compiler but this is deprecated and may be removed in the future
DELETED the special member function is defined by the compiler as deleted

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.