About the C + + display call destructor trap

Source: Internet
Author: User

First, the article for the reason

Now writing a project requires a multi-tree storage structure, but at some point I need to destroy the tree, which means that if I create a new tree object, I would probably want to end the declaration cycle of this object somewhere, and naturally think of displaying the call destructor, but it pulls out such a large trap.

Second, the reason

Before you learn why you should not easily display the call destructor, take a look at the preliminary knowledge.
In order to understand this problem, we must first understand the concept of "heap" and "stack".

1) heap Area (heap)--usually released by the programmer, if the programmer does not release, the program may end up being recycled by the OS. Note that it is not the same as the heap in the data structure, but the distribution is similar to the linked list.

2) stack (stack)--Automatically allocated by the compiler to release, store the function parameter value, local variable value and so on. It operates in a manner similar to a stack in a data structure.

We construct objects, often in a sentence body, such as functions, judgments, loops, and directly by a pair of "{}" contains the statement body. This object is created in the body of the statement and is destroyed at the end of the statement body. The problem is that such objects exist on the stack in the life cycle. In other words, how to manage, is the system complete and the programmer can not control. So, even if we call a destructor, after the end of the object's life cycle, the system will call the destructor again, destroy it on the stack, and realize the real destructor.

So, if we have a statement in the destructor that clears the heap data, calling two times means trying to clean up the data that has already been cleaned out and no longer exists at all! This is a problem that can cause a run-time error and will not be told when compiling!

Third, show the consequences of the call

If the hard to display the call destructor, it is not possible, but there are 3 consequences:

1) when explicitly called, a destructor is equivalent to a normal member function ;

2) The compiler implicitly calls the destructor, such as allocating a memory, and explicitly invoking the destructor, which causes the duplicate -free heap memory exception ;

3) Consider an object to occupy a portion of the stack memory, occupy a portion of the heap of memory (if requested), so as to understand the problem, the system implicitly call the destructor, will be added to release the Stack memory action (and heap memory is manually released by the user); When the user explicitly calls the destructor, Simply executes the statement within the destructor, does not release the stack memory, and does not destroy the object .

This is indicated by the following code:

Example 1:

class aaa{public:    aaa(){}    ~aaa(){cout<<"deconstructor"//析构函数    void disp(){cout<<"disp"<<endl;}private:    char *p;};void main(){aaa a;a.~aaa();a.disp();}

Analysis:

In this case, the explicit two times destructor, the first destructor is equivalent to call a normal member function, execute function inside the statement, show the second destructor is the compiler implicit call, increase the release stack memory action, this class did not request heap memory, so the object cleanly destroyed, explicit + object destroy

Example 2:

class aaa{public:    newchar[1024//申请堆内存    ~aaa(){cout<<"deconstructor"delete []p;}    void disp(){cout<<"disp"<<endl;}private:    char *p;};void

Analysis:

In this case, the first explicit invocation of the destructor, the equivalent of calling a normal member function, executing a function statement, freeing up the heap memory, but did not release the stack memory , the object is still present (but is incomplete, there is unsafe factor); the second time the destructor is called, the heap memory is freed again (the exception is reported). Then release the stack memory, object destroy

Iv. mistakes of the wonderful flowers

Under what circumstances does the system not automatically call destructors? Obviously, if an object is built on a heap, the system is not automatically called. A common example is the new...delete combination. However, the destructor is automatically called when the delete is called. The rare exception to this is the fact that, when using layout new, a destructor that needs to be called explicitly before the cache of the delete setting is really rare.

After I build on the stack, the call destructor is displayed, the object address is present, and even the node can be inserted inside ...

In fact, it's best to look at the data on the heap before it's been released.

/////////  /a.hpp#ifndef a_hpp#define a_hpp#include <iostream>usingNamespace Std;class a{Private:intAint* TEMP;BOOLheap_deleted; Public:A(int_A); AConsta& _a); ~a ();voidChangeintx);voidShow ()Const;};#endif ////////  a.cpp#include "a.hpp"A::a (int_a): heap_deleted (false) {temp =New int;    *temp = _a;    A = *temp; cout<<"A constructor!"<< Endl; }a::a (Consta& _a): heap_deleted (false) {temp =New int;    *temp = _A.A;    A = *temp; cout <<"A Copy Constructor"<< Endl;} A::~a () {if(heap_deleted = =false) {cout <<"temp at:"<< temp << Endl;        Delete temp; heap_deleted =true; cout <<"Heap deleted!\n"; }Else{cout <<"Heap already deleted!\n"; } cout <<"A destroyed!"<< Endl; }voidA::change (intX) {a = x;}voidA::show ()Const{cout <<"a ="<< a << Endl;}////////  //main.cpp#include "a.hpp"intMainintargcChar* argv[]) {A A (1);    A.~a ();    A.show (); cout <<"Main () end\n"; A.change (2); A.show ();return 0;}
V. Summary

So, generally don't be smart to show the call destructor.

-end-

Reference documents

[1] http://blog.csdn.net/todototry/article/details/1483614
[2] Http://club.topsage.com/thread-2228024-1-1.html

Copyright NOTICE: Welcome Reprint, note The source is good! If you do not like please leave a message to explain why again step on Oh, thank you, I can also know the reason, continuous progress!!

About the C + + display call destructor trap

Related Article

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.