C++MemoryManagementC++記憶體管理
來源:互聯網
上載者:User
ProblemC++hasseveraldistinctmemoryareaswhereobjectsandnon-objectvaluesmaybestored,andeachareahasdifferentcharacteristics.Nameasmanyofthedistinctmemoryareasasyoucan.Foreach,summarizeitsperformancecharacteristicsanddescribethelifetimeofobjectsstoredthere.Example:Thestackstoresautomaticvariables,includingbothbuiltinsandobjectsofclasstype.SolutionThefollowingsummarizesaC++program'smajordistinctmemoryareas.Notethatsomeofthenames(e.g.,"heap")donotappearassuchinthedraft
[standard].MemoryAreaCharacteristicsandObjectLifetimes--------------------------------------------------------------ConstDataTheconstdataareastoresstringliteralsandotherdatawhosevaluesareknownatcompiletime.Noobjectsofclasstypecanexistinthisarea.Alldatainthisareaisavailableduringtheentirelifetimeoftheprogram.Further,allofthisdataisread-only,andtheresultsoftryingtomodifyitareundefined.Thisisinpartbecauseeventheunderlyingstorageformatissubjecttoarbitraryoptimizationbytheimplementation.Forexample,aparticularcompilermaystorestringliteralsinoverlappingobjectsifitwantsto.StackThestackstoresautomaticvariables.Typicallyallocationismuchfasterthanfordynamicstorage(heaporfreestore)becauseamemoryallocationinvolvesonlypointerincrementratherthanmorecomplexmanagement.Objectsareconstructedimmediatelyaftermemoryisallocatedanddestroyedimmediatelybeforememoryisdeallocated,sothereisnoopportunityforprogrammerstodirectlymanipulateallocatedbutuninitializedstackspace(barringwillfultamperingusingexplicitdtorsandplacementnew).FreeStoreThefreestoreisoneofthetwodynamicmemoryareas,allocated/freedbynew/delete.Objectlifetimecanbelessthanthetimethestorageisallocated;thatis,freestoreobjectscanhavememoryallocatedwithoutbeingimmediatelyinitialized,andcanbedestroyedwithoutthememorybeingimmediatelydeallocated.Duringtheperiodwhenthestorageisallocatedbutoutsidetheobject'slifetime,thestoragemaybeaccessedandmanipulatedthroughavoid*butnoneoftheproto-object'snonstaticmembersormemberfunctionsmaybeaccessed,havetheiraddressestaken,orbeotherwisemanipulated.HeapTheheapistheotherdynamicmemoryarea,allocated/freedbymalloc/freeandtheirvariants.Notethatwhilethedefaultglobalnewanddeletemightbeimplementedintermsofmallocandfreebyaparticularcompiler,theheapisnotthesameasfreestoreandmemoryallocatedinoneareacannotbesafelydeallocatedintheother.Memoryallocatedfromtheheapcanbeusedforobjectsofclasstypebyplacement-newconstructionandexplicitdestruction.Ifsoused,thenotesaboutfreestoreobjectlifetimeapplysimilarlyhere.Global/StaticGlobalorstaticvariablesandobjectshavetheirstorageallocatedatprogramstartup,butmaynotbeinitializeduntilaftertheprogramhasbegunexecuting.Forinstance,astaticvariableinafunctionisinitializedonlythefirsttimeprogramexecutionpassesthroughitsdefinition.Theorderofinitializationofglobalvariablesacrosstranslationunitsisnotdefined,andspecialcareisneededtomanagedependenciesbetweenglobalobjects(includingclassstatics).Asalways,uninitializedproto-objects'storagemaybeaccessedandmanipulatedthroughavoid*butnononstaticmembersormemberfunctionsmaybeusedorreferencedoutsidetheobject'sactuallifetime.NoteaboutHeapvs.FreeStore:Wedistinguishbetween"heap"and"freestore"becausethedraftdeliberatelyleavesunspecifiedthequestionofwhetherthesetwoareasarerelated.Forexample,whenmemoryisdeallocatedviaoperatordelete,18.4.1.1states:Itisunspecifiedunderwhatconditionspartorallofsuchreclaimedstorageisallocatedbyasubsequentcalltooperatorneworanyofcalloc,malloc,orrealloc,declaredin<cstdlib>.Similarly,itisunspecifiedwhethernew/deleteisimplementedintermsofmalloc/freeorviceversainagivenimplementation.Effectively,thetwoareasbehavedifferentlyandareaccesseddifferently--sobesuretousethemdifferently!