C + + constructor failure __jquery

Source: Internet
Author: User

Any function may fail, and no other constructor, such as a new object or space, is unsuccessful. When the constructor fails, many times we do not want the object to be generated, and at this point we can throw an exception in the constructor. C + + stipulates that after the constructor throws an exception, the object will not be created and the destructor will not be executed, but the successful part (such as a class member variable) that has been created will be partially reverse-structured without a memory leak. But some resources need to be cleaned up before throwing an exception, such as opening a successful file, preferably shutting it down and throwing an exception (although the system will also reclaim the resource), because the destructor will not be executed after the exception is thrown.

On-Line Comparison Classics summary

(1) The only way to notify 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 level know that the constructor failed, although the constructor does not return a value, we can pass a reference value in the constructor, and then set the state inside, After you run the constructor, you can still know if it failed, but in this case the object is actually constructed, but the resource allocation fails, and the destructor executes. This does not match the original intention of our construction failure to generate an 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 been produced will still be reverse-structured)
(3) When the object is partially constructed, the already constructed child object will be reconstructed in reverse order;


An example on the Web

Construction of an instance object
The first step, allocate enough memory, if the failure is 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 succeeds, enter the second step.

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

T *p = new T;

will be transformed by the compiler to look like this: (in fact, we have the same thought process of releasing the resources we have applied for ourselves).

The first step is to allocate the original memory, and if it fails, throw the Bad_alloc exception
try {
    //Step two, call the constructor construct object
    new (p) T;       Placement NEW: Only call constructor for T
(...) {
    delete []p;     Releases the memory throw that the first step allocates
    ;          Flip exception to notify application
}

The second step is to call the constructor, and in general, if the constructor is empty or dynamic memory allocation is not performed, you don't have to care about memory leaks.
What you need to be concerned about is dynamic memory allocation in the constructor
Class A
{
  char* str[10];
Public:
  A () {for
    (int i=0;i<10;i++)
       str[i]=null;     Initialization of str[], this is necessary, or else there will be a problem after the delete
    try{for
      (int i=0;i<10;i++)
      str[i]=new char[1024*1024*1024];   Come on. Hard
    }
    catch (Bad_alloc) {for
       (int i=0;i<10;i++)
           delete []str[i];  Rest assured, even 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
    (int i=0;i<10;i++)
     delete []str[i];         
  } 
;
int main ()
{
    A *pa=null;
    try{
      pa=new A;
    }
    catch (Bad_alloc) {
       cout<< "out of Memory" <<endl;
    }
    Delete PA;
    return 0;
}

The PA is initialized with NULL, even if the first step fails when allocating memory to a, which does not cause subsequent delete PA errors.


There are generally two ways that a constructor might fail

1. Throws an exception in the constructor, the object construct is not completed, and its destructor is not invoked. Of course, we are obligated to release the resources that have been allocated. Simple, most common.
2. The initialization of the resource is placed in another separate function, such as BOOL init (...), called by the creator of the object (such as the Factory method), and then the Init method. Common in ATL.


Turn from: http://blog.csdn.net/wind19/article/details/8213114

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.