Tải bản đầy đủ - 0 (trang)
Chapter 93.  Avoid using static_cast on pointers

Chapter 93.  Avoid using static_cast on pointers

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

Summary

Pointerstodynamicobjectsdon'tstatic_cast:Safe

alternativesrangefromusingdynamic_casttorefactoringto

redesigning.



Discussion

Considerreplacingusesofstatic_castwithitsmorepowerful

relativedynamic_cast,andthenyouwon'thavetoremember

whenstatic_castissafeandwhenit'sdangerous.Although

dynamic_castcanbeslightlylessefficient,italsodetectsillegal

casting(anddon'tforgetItem8).Usingstatic_castinsteadof

dynamic_castislikeeliminatingthestairsnight-light,riskinga

brokenlegtosave90centsayear.

Prefertodesignawaydowncasting:Refactororredesignyour

codesothatitisn'tneeded.Ifyouseethatyouarepassinga

BasetoafunctionthatreallyneedsaDerivedtodoitswork,

examinethechainofcallstoidentifywheretheneededtype

informationwaslost;often,changingacoupleofprototypes

leadstoanexcellentsolutionthatalsoclarifiesthetype

informationflowtoyou.

Excessivedowncastsmightindicatethatthebaseclassinterface

istoosparse.Thiscanleadtodesignsthatdefinemore

functionalityinderivedclasses,andthendowncasteverytime

theextendedinterfaceisneeded.Theonegoodsolutionisto

redesignthebaseinterfacetoprovidemorefunctionality.

If,andonlyif,theoverheadofthedynamic_castactually

matters(seeItem8),considerdefiningyourowncastthatuses

dynamic_castduringdebuggingandstatic_castinthe"all

speednoguarantees"mode(see[Stroustrup00]):



templateTochecked_cast(From*from)

assert(dynamic_cast(from)==static_cast(from)&&"ch

returnstatic_cast(from);

}



templateTochecked_cast(From&from)

assert(dynamic_cast(from)==static_cast(from)&&"ch



returnstatic_cast(from);

}



Thislittleduooffunctions(oneeachneededforpointersand

references)simplytestswhetherthetwocastsagree.Weleave

ituptoyoutocustomizechecked_castforyourneeds,orto

useoneprovidedbyalibrary.



References

[Dewhurst03]Đ29,Đ35,Đ41[Meyers97]Đ39[Stroustrup00]

Đ13.6.2[Sutter00]Đ44



94.Avoidcastingawayconst

Summary

Discussion

Exceptions

References



Summary

Somefibsarepunishable:Castingawayconstsometimes

resultsinundefinedbehavior,anditisastapleofpoor

programmingstyleevenwhenlegal.



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

Chapter 93.  Avoid using static_cast on pointers

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

×