Tải bản đầy đủ - 0 (trang)
Chapter 98.  Don't use varargs (ellipsis)

Chapter 98.  Don't use varargs (ellipsis)

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

Summary

Ellipsescausecollapses:Theellipsisisadangerouscarryover

fromC.Avoidvarargs,andusehigher-levelC++constructsand

librariesinstead.



Discussion

Functionstakingavariablenumberofargumentsareanice

commodity,butC-stylevarargsaren'tthewaytogetthem.

Varargshavemanyseriousshortcomings:

Lackoftypesafety:Essentially,theellipsistellsthe

compiler:"Turnallcheckingoff.I'lltakeoverfromhereand

startreinterpret_casting."(SeeItem92.)

Tightcouplingandrequiredmanualcooperationbetween

callerandcallee:Thelanguage'stypecheckinghasbeen

disabled,sothecallsitemustusealternatewaysto

communicatethetypesoftheargumentsbeingpassed.

Suchprotocols(e.g.,printf'sformatstring)arenotoriously

error-proneandunsafebecausetheycannotbefully

checkedorenforcedbyeitherthecallerorthecallee.(See

Item99.)

Undefinedbehaviorforobjectsofclasstype:Passing

anythingbutprimitiveandPOD(plainolddata)typesvia

varargshasundefinedbehaviorinC++.Unfortunately,most

compilersdon'tgiveawarningwhenyoudoit.

Unknownnumberofarguments:Foreventhesimplest

variable-argumentsfunction(e.g.,min)withavariable

numberofargumentsofknowntype(e.g.,int),youstill

needtohaveaprotocolforfiguringoutthenumberof

arguments.(Ironically,thisisagoodthingbecauseit

furtherdiscouragesusingvarargs.)

Avoidusingvarargsinyourfunctions'signatures.Avoidcalling

functionswithvarargsintheirownsignatures,includinglegacy

functionsandstandardClibraryfunctionssuchassprintf.



Admittedly,callstosprintfcanoftenlookmorecompactand

easiertoreadthanequivalentcallsusingstringstream

formattingandoperator<
hopintoacarwithoutpeskysafetybeltsandbumpers.The

risksarejustnotworthit.printf-relatedvulnerabilities

continuetobeaserioussecurityproblematthetimeofthis

writing(see[Cowan01]),andanentiresubindustryoftools

existstohelpfindsuchtypeerrors(see[Tsai01]).

Prefertousetype-safelibrariesthatsupportvariablearguments

usingothermeans.Forexample,the[Boost]formatlibrary

usesadvancedC++featurestocombinesafetywithspeedand

convenience.



References

[Boost][Cowan01][Murray93]Đ2.6[Sutter04]Đ2-3

[Tsai01]



99.Don'tuseinvalidobjects.Don'tuse

unsafefunctions

Summary

Discussion

References



Summary

Don'tuseexpiredmedicines:Bothinvalidobjectsandhistorical

butunsafefunctionswreakhavoconyourprogram'shealth.



Discussion

Therearethreemajorkindsofinvalidobjects:

Destroyedobjects:Typicalexamplesareautomaticobjects

thathavegoneoutofscopeanddeletedheap-based

objects.Afteryoucallanobject'sdestructor,itslifetimeis

overanditisundefinedandgenerallyunsafetodoanything

withit.

Semanticallyinvalidatedobjects:Typicalexamplesinclude

danglingpointerstodeletedobjects(e.g.,apointerpafter

adeletep;)andinvalidatediterators(e.g.,a

vector::iteratoriafteraninsertionatthebeginning

ofthecontainertheiteratorrefersinto).Notethatdangling

pointersandinvalidatediteratorsareconceptuallyidentical,

andthelatteroftendirectlycontaintheformer.Itis

generallyundefinedandunsafetodoanythingexcept

assignanothervalidvaluetoaninvalidatedobject(e.g.,p

=newObject;ori=v.begin();).

Objectsthatwerenevervalid:Examplesincludeobjects

"obtained"byforgingapointer(usingreinterpret_cast,

seeItem92),oraccessingpastarrayboundaries.

Beawareofobjectlifetimesandvalidity.Neverdereferencean

invaliditeratororpointer.Don'tmakeassumptionsaboutwhat

deletedoesanddoesn'tdo;freedmemoryisfreed,and

shouldn'tbesubsequentlyaccessedunderanycircumstances.

Don'ttrytoplaywithobjectlifetimebycallingthedestructor

manually(e.g.,obj.~T())andthencallingplacementnew.(See

Item55.)

Don'tusetheunsafeClegacy:strcpy,strncpy,sprintf,or



anyotherfunctionsthatdowritetorange-uncheckedbuffers,

and/ordonotcheckandcorrectlyhandleout-of-boundserrors.

C'sstrcpydoesnotchecklimits,and[C99]'sstrncpychecks

limitsbutdoesnotappendanullifthelimitishit;bothare

crasheswaitingtohappenandsecurityhazards.Usemore

modern,safer,andmoreflexiblestructuresandfunctions,such

asthosefoundintheC++standardlibrary(seeItem77).They

arenotalwaysperfectlysafe(forthesakeofefficiency),but

theyaremuchlesspronetoerrorsandcanbebetterusedto

buildsafecode.



References

[C99][Sutter00]Đ1[Sutter04]Đ2-3



100.Don'ttreatarrayspolymorphically

Summary

Discussion

References



Summary

Arraysareill-adjusted:Treatingarrayspolymorphicallyisa

grosstypeerrorthatyourcompilerwillprobablyremainsilent

about.Don'tfallintothetrap.



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

Chapter 98.  Don't use varargs (ellipsis)

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

×