Constructor failed _ Throw exception

Source: Internet
Author: User

Online Comparison of classic summary:

Any function can fail, and the constructor is not otherwise, such as the new object or the space is unsuccessful. When the constructor fails, there are many times when we don't want the object to be generated, and we can throw an exception in the constructor. After the C + + rule constructor throws an exception, the object will not be created, and the destructor will not be executed, but the part that has been created (such as a class member variable) is partially reversed and does not result in a memory leak. However, some resources need to be cleaned out before throwing an exception, such as opening a successful file, and it is best to close and then throw the exception (although the system will also recycle the resource), because the destructor will not be executed after the exception is thrown.

(1) The only way to notify the object construction failure in C + + is to throw an exception in the constructor; (This is not to say that we only have this method to let the upper class know that the constructor failed, although the constructor does not return a value, we can simply pass in a reference value in the constructor, and then set the state inside, After running the constructor you can still know whether the failure, but in this case the object is actually constructed, but there is a resource allocation failure in it, and the destructor will be executed. This does not match the original intention of our failure to build the object. )

(2) Throwing an exception in the constructor will cause the object's destructor to not be executed; (but some of the member variables that have already been produced are still reversed)
(3) When the object is partially constructed, the sub-objects that have been constructed will be destroyed in reverse order;

A chestnut on the net:

The construction of an instance object:
The first step, allocate enough memory, if the failure is the stack overflow or throw std::bad_alloc exception, so in this step you do not have to worry about memory leaks, and this step you can not intervene, if this step success, go to the second step.

The implementation of the new operator guarantees that a memory leak does not occur. For example

T *p = new T;

will be converted by the compiler to look like this: (In fact, we release the resources we have applied to the thought process is the same)

// The first step is to allocate the original memory and throw a Bad_alloc exception if it fails Try {    //  Second step, call constructor construct object    new (p) T;       // Placement NEW: Only the constructor of T is called }catch(...) {    delete []p;      // Release the memory    allocated for the first step throw;          // re-throwing exceptions, notifying the application }
The second step, call the constructor, in general, if the constructor is empty or not dynamic memory allocation, you do not care about the memory leaks
You need to be concerned that there is dynamic memory allocation in the constructor
classa{Char* str[Ten]; Public: A () { for(intI=0;i<Ten; i++) Str[i]=null;//str[] Initialization, this is necessary, or else the delete will cause problems    Try{       for(intI=0;i<Ten; i++) Str[i]=New Char[1024x768*1024x768*1024x768];//It's going to be tough.    }    Catch(bad_alloc) { for(intI=0;i<Ten; i++) Delete []str[i]; //rest assured, even if the delete null is not a problem       Throw;//throws this bad_alloc, this is the exception that the constructor throws, the outer layer is caught, and the destructor is not called    }  }  ~A () { for(intI=0;i<Ten; i++) Delete []str[i]; } };intMain () {A*pa=NULL; Try{PA=NewA; }    Catch(bad_alloc) {cout<<"Out of memory"<<Endl;    } Delete PA; return 0;}
The PA is initialized with null, and does not cause a subsequent delete PA error, even if it fails to allocate memory for a (the first step).

There are two common ways that a constructor might fail

1. Throws an exception in the constructor, the object construct is not completed, and its destructor is not called. Of course, we are obliged to release the resources that have been allocated. Simple, most common.
2. Place the initialization of the resource in a separate function, such as the BOOL init (...), called by the object Creator (such as the Factory method) before calling the Init method. Common in ATL.

Constructor failed _ Throw exception

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.