Thoughts on the C + + goto statement

Source: Internet
Author: User
Tags goto

After work, in the reading of the code written by foreigners, found a very interesting thing, we often say goto statement is harmful, mainly it jumps to jump, upset logic. But Goto also has benefits, such as single-exit, unified freeing of memory aspects, the next look at a function of MAPI initialization

intMapiinit () {intResult =Dt_error; HRESULT HRESULT=S_FALSE; HANDLE Hlock=NULL; BOOL bLocked=FALSE; DWORD RC=wait_timeout; StaticLPCTSTR Szlockname = _t ("Mapiinit"); Hlock=CreateMutex (null,false,szlockname); if(!Hlock) {        Gotoerror; } RC= WaitForSingleObject (Hlock,0); if(rc = =wait_object_0) {bLocked=TRUE; }    if(!M_COINITD) {HResult=CoInitialize (NULL); if(HResult! =S_OK) {            Gotoerror; } M_COINITD=TRUE; }    if(!M_MAPIINITD) {HResult=mapiinitialize (NULL); if(HResult! =S_OK) {            Gotoerror; } M_MAPIINITD=TRUE; } Result=Dt_ok;done:if(hlock) {if(bLocked) {ReleaseMutex (hlock);    } closehandle (Hlock); }    returnResult;error:result=Dt_error; GotoDone ;}

Two Goto, one done, one error,done is mainly responsible for the release of memory resources, error is mainly assignment results and return done.

In other words, if the program does not conform to our direction, we will log, and then goto error, instead of return, if return, then release the resources to do?

The biggest benefit of Goto done is that you don't have to go around freeing up memory. If more exports, to release more content, full of free memory, and do not know if there is no leakage within.

Thoughts on the C + + goto statement

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.