Effective C + + Note two construction/destructor/assignment operations

Source: Internet
Author: User

Article 05: Understand what functions C + + silently writes and calls

The compiler defaults to declaring a default constructor, a copy constructor, a copy assignment operator, and a destructor. These functions are both public and inline.

 1  class   Empty { 2  public  :  3   Empty () {...}  4  Empty (const  empty& RHS) {...}  5  ~empty () {...}  6  empty& operator  = (const  empty& RHS) {...}  7 }; 

If you intend to support assignment operations within a class containing reference members, you must define the copy assignment operator yourself. If a base classes declares the copy assignment operator as private, the compiler will refuse to generate a copy assignment operator for its derived classes.

Remember:

The compiler can secretly create a default constructor, a copy constructor, a copy assignment operator, and a destructor for class.

Article 06: If you do not want to use the compiler automatically generated functions, you should explicitly deny

If you do not declare a copy constructor or copy assignment operator, the compiler may produce a copy for you, and your classes supports copying. All compiler-produced functions are public. To prevent these functions from being created, declare them as private. But the member function and the friend function can still call your private function. If you don't define them, you get a connection error when someone accidentally calls.

It is possible to move the connection period error to the compile time. Design a base class that blocks copying operations.

 1  class   uncopyable { 2  protected  :  3   Uncopyable () {}  4  ~uncopyable () {}  5  private  :  6  uncopyable (const  uncopyable&);  7  uncopyable& operator  = (const  uncopyable&);  8 }; 

Remember:

To dismiss a function that the compiler automatically provides, the corresponding member function can be declared private and not implemented. Using a base class like uncopyable is also a practice.

Article 07: Declaring a virtual destructor for a polymorphic base class

When the derived class object is deleted through a base class pointer, and the base class carries a non-virtual destructor, the result is undefined.

Give base Class A virtual destructor. Deleting the derived class object later will be as you would like.

Any class with the virtual function is almost certain that there should be a virtual destructor as well. When class does not attempt to be treated as a base class, making its destructor virtual is often a bad idea.

To implement the virtual function, an object must carry certain information, which is used primarily to determine which virtual function is called at run time. This information is usually pointed out by a so-called vptr (virtual table pointer) pointer. Vptr points to an array of function pointers, called VTBL (virtual table), and each class with the virtual function has a corresponding VTBL. When an object calls a virtual function, the actual function that is called depends on the VTBL that the object refers to, and the compiler looks for the appropriate function pointer in the VPTR. If class contains virtual functions, the volume of its objects increases.

Declare a pure virtual destructor for the class that you want it to be called abstract.

1 class Awov {2public:3     virtual ~awov () =0; 4 }; 5 Awov::~awov () {}

The destructor works by the deepest derived class whose destructor is called First, followed by the destructor of each of its base class. A virtual destructor for base classes, this rule applies only to base classes with polymorphic properties. This base classes is designed to be used to process derived class objects through the base class interface. Not all base classes are designed for polymorphic purposes.

Remember:

A base classes with polymorphic properties should declare a virtual destructor. If class has any virtual functions, he should have a virtual destructor.

The purpose of classes is not to declare a virtual destructor if it is not used as a base classes, or not for polymorphism.

Article 08: Don't let exceptions escape destructors

C + + does not prohibit destructors from projecting exceptions, but it does not encourage you to do so. In the case of two exceptions, if the program is not finished, it leads to ambiguous behavior.

Forcing the end of a program is a reasonable option if the program cannot continue execution after encountering an error that occurred during the destruction period. Swallowing an exception is a bad idea, and it suppresses important information about the failure of certain actions.

A better strategy is to redesign the interface to give its customers the opportunity to respond to possible problems.

Remember:

Destructors should never spit out exceptions. If a function called by a destructor might run out of an exception, the destructor should catch any exceptions and then swallow them or end the program.

If the customer needs to react to an exception thrown during the operation of an action function, then class should provide a normal function to perform the operation.

Article 09: Never call the virtual function in the construction and destruction process

The virtual function will never descend to the derived classes stratum during the base class construction. During the base class construction of the derived class object, the object's type is base class rather than derived class. Not only will the virtual function be parsed by the compiler to the base class, but the object will also be treated as a base class type if the run-time type information is used.

The same principle applies to destructors as well. Once the derived class destructor starts executing, the derived class member variables within the object render undefined values, so C + + sees them as if they no longer exist. After entering the base class destructor, the object becomes a base class object.

Since you cannot use the virtual function to call down from base classes, during construction, you can compensate by making derived classes pass the necessary construction information up to the base class constructor instead.

Remember:

Do not call the virtual function during construction and destruction, because such calls never fall to derived class.

Clause 10: Make operator= return a reference to *this

In order to implement the chained assignment, the assignment operator must return a reference to the left argument of the operator. This is the protocol you should follow when implementing the assignment operator for classes.

1 class Widget {2public:3     operator= (const widget& RHS) {4        ... 5         return *this; 6     }7 };

This Protocol applies not only to the standard assignment form above, but also to all assignment-related operations.

Remember:

The other assignment operator returns a reference to *this.

Article 11: Handling Self-assignment in operator=

Self-assignment occurs when an object is assigned to itself.

In order to prevent such errors, the traditional practice is to test the self-assignment by operator= one of the first cards.

1     operator= (const widget& RHS) {2         if (thisreturn *this; 3         ... 4         return *this; 5     }

This version still does not have the exception security, but lets the operator= have the exception security often automatically obtains the self-assignment security The return.

Another alternative is to use the copy and swap technique.

1 class Widget {2public:3     operator= (const widget& RHS) {4        Widget temp (RHS); 5         Swap (temp); 6         return *this; 7     }8 };

Remember:

Make sure that operator= has good behavior when the object is self-assigned. Techniques include comparing the address of the source object and target object, the thoughtful sequence of statements, and the Copy-and-swap.

Determines if any function operates on more than one object, and when multiple objects are the same object, its behavior is still correct.

Article 12: Do not forget every ingredient when copying an object

Since you refuse the compiler to write copying functions for you, they will not tell you if your code is not complete. If you add a member variable for class, you must modify the copying function at the same time.

Whenever you assume the heavy responsibility of writing copying functions for derived class, you must also copy the base class component carefully. You should let derived class's copying function call the corresponding base class function.

When you write a copying function, make sure that: Copy all local member variables, and call all the appropriate copying functions within the base classes.

If you find that your copy constructor and the copy assignment operator have similar code, the practice of eliminating duplicate code is to create a new member to call both. Such functions are often private and often named Init. This strategy can safely eliminate code duplication between the copy constructor and the copy assignment operator.

Remember:

The copying function should ensure that all member variables and all base class components within the object are copied.

Do not attempt to implement another copying function with one of the copying functions. Common functions should be put into the third function and called together by two copying functions.

Effective C + + Note two construction/destructor/assignment operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.