Tải bản đầy đủ - 0 (trang)
Chapter 51.  Destructors, deallocation, and swap never fail

Chapter 51.  Destructors, deallocation, and swap never fail

Tải bản đầy đủ - 0trang

Summary

Everythingtheyattemptshallsucceed:Neverallowanerrorto

bereportedfromadestructor,aresourcedeallocationfunction

(e.g.,operatordelete),oraswapfunction.Specifically,types

whosedestructorsmaythrowanexceptionareflatlyforbidden

fromusewiththeC++standardlibrary.



Discussion

Thesearekeyfunctionsthatmustnotfailbecausetheyare

necessaryforthetwokeyoperationsintransactional

programming:tobackoutworkifproblemsareencountered

duringprocessing,andtocommitworkifnoproblemsoccur.If

there'snowaytosafelybackoutusingno-failoperations,then

no-failrollbackisimpossibletoimplement.Ifthere'snowayto

safelycommitstatechangesusingano-failoperation(notably,

butnotlimitedto,swap),thenno-failcommitisimpossibleto

implement.

Considerthefollowingadviceandrequirementsfoundinthe

C++Standard:

Ifadestructorcalledduringstackunwindingexitswithan

exception,terminateiscalled(15.5.1).Sodestructors

shouldgenerallycatchexceptionsandnotletthem

propagateoutofthedestructor.

[C++03]Đ15.2(3)

NodestructoroperationdefinedintheC++Standard

Library[includingthedestructorofanytypethatisused

toinstantiateastandardlibrarytemplate]willthrowan

exception.

[C++03]Đ17.4.4.8(3)

Destructorsarespecial,andthecompilerinvokesthem

automaticallyinvariouscontexts.Ifyouwriteaclasslet'scallit

Nefariouswhosedestructormightfail(usuallybythrowingan

exception;seeItem72),youincurthefollowingconsequences:

Nefariousobjectsarehardtousesafelyinnormal



functions:Youcan'treliablyinstantiateautomatic

Nefariousobjectsinascopeifthatscopemightbeexited

throughanexception.Ifthathappened,Nefarious's

destructor(automaticallyinvoked)mightattempttothrow

anexceptionaswell,whichwouldresultinsuddendeathof

yourentireprogramviastd::terminate.(SeealsoItem

75)

ClasseswithNefariousmembersorbasesarealsohardto

usesafely:Nefarious'poorbehaviorextendstoanyclass

ofwhichNefariousisamemberorabaseclass.

Youcan'treliablycreateglobalorstaticNefariousobjects

either:Anyexceptionitsdestructormightthrowcan'tbe

caught.

Youcan'treliablycreatearraysofNefarious:Inshort,the

behaviorofarraysisundefinedinthepresenceof

destructorsthatthrowbecausethereisnoreasonable

rollbackbehaviorthatcouldeverbedevised.(Justthink:

Whatcodecanthecompilergenerateforconstructingan

arrayoftenNefariousobjectswhere,ifthefourthobject's

constructorthrows,thecodehastogiveupandinits

cleanupmodetriestocallthedestructorsofthealreadyconstructedobjectsandoneormoreofthosedestructors

throws?Thereisnosatisfactoryanswer.)

Youcan'tuseNefariousobjectsinstandardcontainers:

Youcan'tstoreNefariousobjectsinstandardcontainersor

usethemwithanyotherpartofthestandardlibrary.The

standardlibraryforbidsalldestructorsusedwithitfrom

throwing.

Deallocationfunctions,includingspecificallyoverloaded

operatordeleteandoperatordelete[],fallintothesame

category,becausetheytooareusedduringcleanupingeneral,



andduringexceptionhandlinginparticular,tobackoutof

partialworkthatneedstobeundone.

Besidesdestructorsanddeallocationfunctions,commonerrorsafetytechniquesrelyalsoonswapoperationsneverfailingin

thiscase,notbecausetheyareusedtoimplementaguaranteed

rollback,butbecausetheyareusedtoimplementaguaranteed

commit.Forexample,hereisanidiomaticimplementationof

operator=foratypeTthatperformscopyconstruction

followedbyacalltoano-failSwap:

T&T::operator=(constT&other){

Ttemp(other);

Swap(temp);

}



(SeealsoItem56.)

Fortunately,whenreleasingaresource,thescopeforfailureis

definitelysmaller.Ifusingexceptionsastheerrorreporting

mechanism,makesuresuchfunctionshandleallexceptionsand

othererrorsthattheirinternalprocessingmightgenerate.(For

exceptions,simplywrapeverythingsensitivethatyour

destructordoesinatry/catch()block.)Thisisparticularly

importantbecauseadestructormightbecalledinacrisis

situation,suchasfailuretoallocateasystemresource(e.g.,

memory,files,locks,ports,windows,orothersystemobjects).

Whenusingexceptionsasyourerrorhandlingmechanism,

preferdocumentingthisbehaviorbydeclaringthesefunctions

withacommentedemptyexceptionspecificationof/*throw()

*/.(SeeItem75.)



References

[C++03]Đ15.2(3),Đ17.4.4.8(3)[Meyers96]Đ11

[Stroustrup00]Đ14.4.7,ĐE.2-4[Sutter00]Đ8,Đ16

[Sutter02]Đ18-19



52.Copyanddestroyconsistently

Summary

Discussion

Exceptions

References



Summary

Whatyoucreate,alsocleanup:Ifyoudefineanyofthecopy

constructor,copyassignmentoperator,ordestructor,youmight

needtodefineoneorbothoftheothers.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 51.  Destructors, deallocation, and swap never fail

Tải bản đầy đủ ngay(0 tr)

×