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