Tải bản đầy đủ - 0 (trang)
Chapter 94.  Avoid casting away const

Chapter 94.  Avoid casting away const

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

Summary

Somefibsarepunishable:Castingawayconstsometimes

resultsinundefinedbehavior,anditisastapleofpoor

programmingstyleevenwhenlegal.



Discussion

Onceyougoconst,you(should)nevergoback.Ifyoucast

awayconstonanobjectwhoseoriginaldefinitionreallydid

defineittobeconst,allbetsareoffandyouareinundefined

behaviorland.Forexample,compilerscan(anddo)put

constantdataintoROMorwrite-protectedRAMpages.Casting

awayconstfromsuchatrulyconstobjectisapunishablelie,

andoftenmanifestsasamemoryfault.

Evenwhenitdoesn'tcrashyourprogram,castingawayconstis

abrokenpromiseanddoesn'tdowhatmanyexpect.For

example,thisdoesn'tallocateavariable-sizedarray:



voidFoolish(unsignedintn){

constunsignedintsize=1;

const_cast(size)=n;//bad:don'tdothis

charbuffer[size];//willalwayshaves

//

}



C++hasoneimplicitconst_cast,the"conversionofdeath"

fromastringliteraltochar*:

char*weird="Trickortreat?";



Thecompilerperformsasilentconst_castfromconst

char[16]tochar*.ThiswasallowedforcompatibilitywithC

APIs,butit'saholeinC++'stypesystem.Stringliteralsare

ROM-able,andtryingtomodifythestringisliabletocausea

memoryfault.



Exceptions

Castingawayconstcanbenecessarytocallconst-incorrect

APIs(seeItem15).Itisalsousefulwhenafunctionthatmust

takeandreturnthesamekindofreferencehasconstandnonconstoverloads,implementedbyhavingonecalltheother:

constObject&f(constObject&);



Object&f(Object&obj){

constObject&ref=obj;

returnconst_cast(foo(ref));//havetoconst_ca

}



References

[Dewhurst03]Đ32,Đ40[Sutter00]Đ44



95.Don'tuseC-stylecasts

Summary

Discussion

References



Summary

Agedoesn'talwaysimplywisdom:C-stylecastshavedifferent

(andoftendangerous)semanticsdependingoncontext,all

disguisedbehindasinglesyntax.ReplacingC-stylecastswith

C++-stylecastshelpsguardagainstunexpectederrors.



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

Chapter 94.  Avoid casting away const

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

×