Tải bản đầy đủ - 0 (trang)
Chapter 25.  Take parameters appropriately by value, (smart) pointer, or reference

Chapter 25.  Take parameters appropriately by value, (smart) pointer, or reference

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

Summary

Parameterizewell:Distinguishamonginput,output,and

input/outputparameters,andbetweenvalueandreference

parameters.Takethemappropriately.



Discussion

Choosingwellamongvalues,references,andpointersfor

parametersisgoodhabitthatmaximizesbothsafetyand

efficiency.

Althoughefficiencyshouldnotbeourprimaryup-frontconcern

(seeItem8),neithershouldwewriteneedlesslyinefficientcode

whenallotherthings,includingclarity,areequal(seeItem9).

Prefertofollowtheseguidelinesforchoosinghowtotake

parameters.Forinput-onlyparameters:

Alwaysconst-qualifyallpointersorreferencestoinput-only

parameters.

Prefertakinginputsofprimitivetypes(e.g.,char,float)

andvalueobjectsthatarecheaptocopy(e.g.,Point,

complex)byvalue.

Prefertakinginputsofotheruser-definedtypesby

referencetoconst.

Considerpass-by-valueinsteadofreferenceifthefunction

requiresacopyofitsargument.Thisisconceptually

identicaltotakingareferencetoconstplusdoingacopy,

anditcanhelpcompilertobetteroptimizeaway

temporaries.

Foroutputorinput/outputparameters:

Preferpassingby(smart)pointeriftheargumentisoptional

(socallerscanpassnullasa"notavailable"or"don'tcare"

value)orifthefunctionstoresacopyofthepointeror



otherwisemanipulatesownershipoftheargument.

Preferpassingbyreferenceiftheargumentisrequiredand

thefunctionwon'tstoreapointertoitorotherwiseaffect

itsownership.Thisstatesthattheargumentisrequiredand

makesthecallerresponsibleforprovidingavalidobject.

Don'tuseC-stylevarargs(seeItem98).



References

[Alexandrescu03a][Cline99]Đ2.10-11,14.02-12,32.08

[Dewhurst03]Đ57[Koenig97]Đ4[Lakos96]Đ9.1.11-12

[McConnell93]Đ5.7[Meyers97]Đ21-22[Stroustrup94]

Đ11.4.4[Stroustrup00]Đ5.5,Đ11.6,Đ16.3.4[Sutter00]Đ6,

Đ46



26.Preservenaturalsemanticsfor

overloadedoperators

Summary

Discussion

Exceptions

References



Summary

Programmershatesurprises:Overloadoperatorsonlyforgood

reason,andpreservenaturalsemantics;ifthat'sdifficult,you

mightbemisusingoperatoroverloading.



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

Chapter 25.  Take parameters appropriately by value, (smart) pointer, or reference

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

×