Article 05: Understand what functions C + + silently writes and calls
If you do not declare yourself, the compiler will declare a copy constructor for the class (compiler Version), a copy assignment operator, and a destructor.
In addition, if you do not declare any constructors, the compiler will also become a default constructor that you declare. All of these functions are public and inline.
Only when these functions are required (called) will they be created by the compiler. That is, the compiler will create them only if there is a requirement.
Please remember:
- The compiler can secretly create default constructors, copy constructors, copy assignment operators, and destructors for classes.
Article 06: If you do not want to use the compiler automatically generated functions, you should explicitly deny
Usually if you don't want the class to support a particular skill, just do not specify the corresponding function.
However, this strategy has no effect on copy constructors and copy assignment operators. Because the compiler declares them "in a romantic" and calls them when needed.
Because the compiler produces functions that are of the public type, you can declare the copy constructor or copy assignment operator as private.
Pass this little "trick" can prevent people from calling it externally , but member functions and friend functions in a class can still call the private function.
The workaround might be a base class designed specifically to prevent copy actions.
Please remember:
- To dismiss a function that the compiler automatically (secretly) provides, the corresponding member function can be declared private and not implemented.
article 07: Declaring a virtual destructor for a polymorphic base class
When a pointer to a base class points to an object of a derived class, when we are done using it, the result of the call to delete is undefined-the base class component is usually destroyed.
The full potential of derived classes is still in the heap. This is the formation of resource leaks, corrupted data structures, spending a lot of time on the debugger.
Eliminating these problems is simple: give the base class A virtual destructor. Then delete the derived class object as you would like.
When a class is not intended to be used as a base class, making its destructor virtual is often a bad idea.
Because the virtual function is implemented, additional overhead is required (pointer vptr to the virtual function table).
STL containers do not have virtual destructors, so it is best not to derive them.
Please remember:
- A base class with polymorphic properties should declare a virtual destructor.
- If a class has any virtual functions, it should have a virtual destructor.
- A class is not designed to be used as a base class, or not to declare a virtual destructor for polymorphism.
article 08: Don't let exceptions escape destructors
//..
Effective C + + 02 construction/destructor/assignment operation (to be continued)