C ++ Summary of precautions related to "class" (8): destructor

Source: Internet
Author: User

1. Fictitious Function Definition

 

A destructor is a special user-defined member function. When an object of this class leaves its domain or delete expression and is applied to the pointer of an object of this class, the Destructor is automatically called. The Destructor name is preceded by the class name ~ It does not return any value or any parameter, because it cannot specify any parameter, so it cannot be overloaded. Although we can define multiple constructors for a class, we can only provide one destructor, which will be applied to all objects of the class. The following are the account class destructor:

Class account {
Public:
Account ();
Explicit account (const char *, double = 0.0 );
Account (const account &);
~ Account ();
//...
PRIVATE:
Char * _ name;
Unsigned int _ acct_nmbr;
Double _ balance;
};
Inline
Account ::~ Account ()
{
Delete [] _ name;
Return_acct_nmbr (_ acct_nmbr );
}

 

Generally, if a data member of a class is stored by value, for example, three coordinate members of point3d, no destructor is required. Not every class requires an destructor, even if one or more constructors are defined for the class, destructor are mainly used to discard the resources obtained from constructors or lifecycles of class objects, such as releasing mutex locks or deleting the memory allocated by the operator new.

 

When the pointer or reference of a class object leaves the domain, the referenced object does not end its life cycle, and the Destructor will not be called.

The C ++ language ensures that the delete operator is not used to delete pointers that do not point to any objects, so we do not need to writeCodeTo ensure this:

// No need -- it is implicitly executed by the compiler.
If (pact! = 0) delete Pact;

Whenever you delete an independent heap object in a function, it is best to use an auto_ptr class object instead of an actual pointer. This is especially true for class objects on the stack. Otherwise, if the delete expression fails to be applied (for example, if an exception is thrown ), this will not only cause memory leakage, but also prevent the Destructor from being called. For example, the following isProgramFor example, it is slightly modified because the auto_ptr object cannot be explicitly reset to point to the second object unless the second auto_ptr is assigned.

 

# Include <memory>
# Include "account. H"
 
Account global ("James Joyce ");
Int main ()
{
Account local ("Anna Livia plurabelle", 10000 );
Account & loc_ref = global;
Auto_ptr <account> Pact (New Account ("Stephen Dedalus "));

{
Account local_too ("Stephen hero ");
}
// The auto_ptr object is destroyed here
}

 

Ii. explicit structure call

 

In some cases, it is necessary to explicitly call the Destructor for a special class object. This often happens when combined with the new operator. Let's look at an example,
When writing:

Char * arena = new char [sizeof image];

In fact, we have allocated a new Heap Storage zone with the same size as the image object. The associated memory zone is not initialized, which is a random bit sequence after the last use. When we write:

Image * PTR = new (ARENA) image ("Quasimodo ")

No new memory is allocated. Instead, PTR is assigned the address associated with arena. With PTR, memory is interpreted as an image object. However, although no memory is allocated, the constructor is applied to the existing storage zone. In fact, positioning the new operator allows us to construct a class object on a specific pre-allocated memory address.

When the Quasimodo image is completed, we may want to operate an Esmerelda image at the same memory location pointed to by arena ). On the one hand, we know how to do this:

Image * PTR = new (ARENA) image ("Esmerelda ");

The problem is that this overwrites the Quasimodo image. We have modified the Quasimodo image and want to store it on the disk. Generally, we do this through the destructor of the image class, but if the application operator delete:

// Poor: the storage zone is also deleted when the Destructor is called.
Delete PTR;

In addition to calling the destructor, we also deleted the underlying Heap Storage zone, which is not what we want. We can explicitly call the image destructor:

PTR-> ~ Image ();

The underlying storage zone can be called by the next Positioning new operator to continue using it.

 
Although PTR and Arena point to the same Heap Storage zone, applying the delete operator on arena makes no sense:

// The Destructor is not called.
Delete arena;

Does not cause the image destructor to be called because the arena type is char *. Remember, the compiler will call the Destructor only when the pointer in the delete expression points to a class type with destructor.
 

3. Possible program code Expansion

 

Undoubtedly, an inline destructor may be a source of program code expansion because it is inserted to every exit point in the function to parse the local class objects of each activity. For example, in the following code segment:

Account Acct ("Tina Lee ");
Int SWT;

//...
Switch (SWT ){
Case 0:
Return;
Case 1:
// Perform the operation
Return;
Case 2:
// Perform other operations
Return;
// Etc.
}

Before each return statement, the Destructor must be expanded in an inline manner. In the case of account class destructor, because of its small length, therefore, the overhead of multiple expansion operations is also small. However, if it is found to be a problem, the solution is: declare the Destructor as non-inline, or rewrite the program code. One possible rewrite scheme is to replace the return statement with the break statement in each case tag, and then introduce a return statement after the switch statement:

 
// Rewrite to provide a return point
Switch (SWT ){
Case 0:
Break;
Case 1:
// Perform the operation
Break;
Case 2:
// Perform other operations
Break;
// Etc.
}
 
// A single return point
Return;

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.