Tải bản đầy đủ - 0 (trang)
Chapter 52.  Copy and destroy consistently

Chapter 52.  Copy and destroy consistently

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

Summary

Whatyoucreate,alsocleanup:Ifyoudefineanyofthecopy

constructor,copyassignmentoperator,ordestructor,youmight

needtodefineoneorbothoftheothers.



Discussion

Ifyouneedtodefineanyofthesethreefunctions,itmeansyou

needittodomorethanitsdefaultbehaviorandthethreeare

asymmetricallyinterrelated.Here'show:

Ifyouwrite/disableeitherthecopyconstructororthecopy

assignmentoperator,youprobablyneedtodothesamefor

theother:Ifonedoes"special"work,probablysoshould

theotherbecausethetwofunctionsshouldhavesimilar

effects.(SeeItem53,whichexpandsonthispointin

isolation.)

Ifyouexplicitlywritethecopyingfunctions,youprobably

needtowritethedestructor:Ifthe"special"workinthe

copyconstructoristoallocateorduplicatesomeresource

(e.g.,memory,file,socket),youneedtodeallocateitinthe

destructor.

Ifyouexplicitlywritethedestructor,youprobablyneedto

explicitlywriteordisablecopying:Ifyouhavetowritea

nontrivialdestructor,it'softenbecauseyouneedto

manuallyreleasearesourcethattheobjectheld.Ifso,itis

likelythatthoseresourcesrequirecarefulduplication,and

thenyouneedtopayattentiontothewayobjectsare

copiedandassigned,ordisablecopyingcompletely.

Inmanycases,holdingproperlyencapsulatedresourcesusing

RAII"owning"objectscaneliminatetheneedtowritethese

operationsyourself.(SeeItem13.)

Prefercompilergeneratedspecialmembers;onlythesecanbe

classifiedas"trivial,"andatleastonemajorSTLvendorheavily

optimizesforclasseshavingtrivialspecialmembers.Thisis



likelytobecomecommonpractice.



Exceptions

Whenanyofthespecialfunctionsaredeclaredonlytomake

themprivateorvirtual,butwithoutspecialsemantics,itdoesn't

implythattheothersareneeded.

Inrarecases,classesthathavemembersofstrangetypes

(e.g.,references,std::auto_ptrs)areanexceptionbecause

theyhavepeculiarcopysemantics.Inaclassholdinga

referenceoranauto_ptr,youlikelyneedtowritethecopy

constructorandtheassignmentoperator,butthedefault

destructoralreadydoestherightthing.(Notethatusinga

referenceorauto_ptrmemberisalmostalwayswrong.)



References

[Cline99]Đ30.01-14[Koenig97]Đ4[Stroustrup00]Đ5.5,

Đ10.4[SuttHysl04b]



53.Explicitlyenableordisablecopying

Summary

Discussion

References



Summary

Copyconsciously:Knowinglychooseamongusingthecompilergeneratedcopyconstructorandassignmentoperator,writing

yourownversions,orexplicitlydisablingbothifcopyingshould

notbeallowed.



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

Chapter 52.  Copy and destroy consistently

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

×