Go to main content
Oracle® Developer Studio 12.5: C++ User's Guide

Exit Print View

Updated: July 2016
 
 

9.3 Using Default Operators

If a class definition does not declare a parameterless constructor, a copy constructor, a copy assignment operator, or a destructor, the compiler will implicitly declare them. These are called default operators. A C-like struct has these default operators. When the compiler builds a default operator, it knows a great deal about the work that needs to be done and can produce very good code. This code is often much faster than user-written code because the compiler can take advantage of assembly-level facilities while the programmer usually cannot. So, when the default operators do what is needed, the program should not declare user-defined versions of these operators.

Default operators are inline functions, so do not use default operators when inline functions are inappropriate (see the previous section). Otherwise, default operators are appropriate in the following situations:

  • The user-written parameterless constructor would call only parameterless constructors for its base objects and member variables. Primitive types effectively have “do nothing” parameterless constructors.

  • The user-written copy constructor would simply copy all base objects and member variables.

  • The user-written copy assignment operator would simply copy all base objects and member variables.

  • The user-written destructor would be empty.

Some C++ programming texts suggest that class programmers always define all operators so that any reader of the code will know that the class programmer did not forget to consider the semantics of the default operators. Obviously, this advice interferes with the optimization discussed above. The resolution of the conflict is to place a comment in the code stating that the class is using the default operator. C++11 allows you to declare the above special functions as default, showing that you did not forget about them, but without incurring any overhead.