如何確保?標(biāo)準(zhǔn)確保。因?yàn)檫@是標(biāo)準(zhǔn)規(guī)定的。以下摘自C++11Standard(draftN3690)15.2Constructorsanddestructors[except.ctor]不光保證了被析構(gòu),還規(guī)定了析構(gòu)的順序。1)Ascontrolpassesfromthepointwhereanexceptionisthrowntoahandler,destructorsareinvokedforallautomaticobjectsconstructedsincethetryblockwasentered.Theautomaticobjectsaredestroyedinthereverseorderofthecompletionoftheirconstruction.比較特殊一點(diǎn)的,如果異常發(fā)生在構(gòu)造或析構(gòu)的時候,其子對象也能確保被正確的析構(gòu)。而該對象本身呢?構(gòu)造的時候它還不存在呢,所以無須擔(dān)心。析構(gòu)的情況會在后面說明。2)Anobjectofanystoragedurationwhoseinitializationordestructionisterminatedbyanexceptionwillhavedestructorsexecutedforallofitsfullyconstructedsubobjects(excludingthevariantmembersofaunion-likeclass),thatis,forsubobjectsforwhichtheprincipalconstructor(12.6.2)hascompletedexecutionandthedestructorhasnotyetbegunexecution.Similarly,ifthenon-delegatingconstructorforanobjecthascompletedexecutionandadelegatingconstructorforthatobjectexitswithanexception,theobject’sdestructorwillbeinvoked.Iftheobjectwasallocatedinanew-expression,thematchingdeallocationfunction(3.7.4.2,5.3.4,12.5),ifany,iscalledtofreethestorageoccupiedbytheobject.這整個過程被稱為"stackunwinding",翻譯過來叫:堆棧輾轉(zhuǎn)開解。3)Theprocessofcallingdestructorsforautomaticobjectsconstructedonthepathfromatryblocktothepointwhereanexceptionisthrowniscalled“stackunwinding.”Ifadestructorcalledduringstackunwindingexitswithanexception,std::terminateiscalled(15.5.1).[Note:Sodestructorsshouldgenerallycatchexceptionsandnotletthempropagateoutofthedestructor.—endnote]注意看那個“Note”,標(biāo)準(zhǔn)對編譯器做了要求,對于析構(gòu)函數(shù)來說,是要對自身負(fù)責(zé)的。正是因?yàn)閟tackunwinding的保證作為基礎(chǔ),才有了我們所熟知的RAII技術(shù)。另外可以注意到,如果在stackunwinding期間拋出異常呢?就只能調(diào)用std::terminate了:15.5.1Thestd::terminate()function[except.terminate]2)Insuchcases,std::terminate()iscalled(18.8.3).Inthesituationwherenomatchinghandlerisfound,itisimplementation-de?nedwhetherornotthestackisunwoundbeforestd::terminate()iscalled.Inthesituationwherethesearchforahandler(15.3)encounterstheoutermostblockofafunctionwithanoexcept-speci?cationthatdoesnotallowtheexception(15.4),itisimplementation-de?nedwhetherthestackisunwound,unwoundpartially,ornotunwoundatallbeforestd::terminate()iscalled.Inallothersituations,thestackshallnotbeunwoundbeforestd::terminate()iscalled.Animplementationisnotpermittedto?nishstackunwindingprematurelybasedonadeterminationthattheunwindprocesswilleventuallycauseacalltostd::terminate()stackunwinding的過程并不保證做完,但最終肯定是要調(diào)用std::terminate來終止。