Post on 01-Jun-2018
8/9/2019 Advanced C++ Topics
1/12
8/9/2019 Advanced C++ Topics
2/12
h*! aroach !u))e!t! a !econd ot*on, one common *n ure C sentinel values- he *dea *! to have
'unct*on! return !ec*al value! *nd*cat*n) ;th*! value *! *nval*d becau!e the 'unct*on 'a*led to e%ecute
correctl&-< +n*t*all&, th*! ma& !eem l*e a )ood *dea *t reort! the error and )*ve! the call*n) 'unct*on a
chan)e to re!ond- Ho"ever, there are !everal maor roblem! "*th th*! aroach- F*r!t, *t mean! that
"e have to de!*)nate a !ec*al return value that the 'unct*on mu!t never return e%cet "hen an erroroccur!- +n the ca!e o' string, th*! *! *n'ea!*ble !*nce *' "e mar !ome string value a! an error let$!
call *t N!"#$%"R"'4, then the u!er could "r*te code l*e th*!
ConcatNCopies(N!"#$%"R"', );
nd the code "ould return N!"#$%"R"' !*nce concatenat*n) N!"#$%"R"' "*th *t!el' one t*me
&*eld! N!"#$%"R"'4 even thou)h the 'unct*on !ucceeded- Second, unle!! "e de'*ne a !tandard*=ed
!&!tem 'or re!erv*n) *nval*d return value!, "e ma& end u "*th a hu)e number o' 'unct*on!, each "*th
the*r o"n !ec*al ;error< return code!, that could lead to roblem! *' "e checed the 'unct*on$! return
value a)a*n!t the "ron) !ent*nel- +ma)*ne the chao! o' con!tant! *RN%ERRR, N!"#$%*RN,
and N!"#$%"R"', each corre!ond*n) to d*''erent 'unct*on!- h*rd, th*! aroach mae! the code
bul&, !*nce "henever "e$d call ConcatNCopies, "e$d have to "r*te !ometh*n) l*e th*!
string result = ConcatNCopies(m-tring, m-nteger);if(result == N!"#$%"R"') { ./ 1an2le error /. }
h*! *! un!*)htl& and, above all, needle!!l& coml*cate! the code-
>et another ot*on m*)ht be to chan)e the 'unct*on declarat*on !o that *t loo! l*e th*!
3ool ConcatNCopies(const string &input, int numRepeats, string &output);
+n!tead o' return*n) a value, *n!tead "e '*ll *n a string !ec*'*ed a! a re'erence arameter and then
return "hether the oerat*on !ucceeded- h*! too ha! *t! 'la"!- Suo!e our 'unct*on *! an overloaded
oerator- e cannot !*ml& chan)e the number o' arameter! to an overloaded oerator, !*nce all
overloaded oerator! e%cet 'or operator () have a '*%ed number o' ar)ument!, and con!e/uentl& th*!aroach "*ll not "or- ll o' the aroache! "e$ve tr*ed !o 'ar have !ome 'la", !o ho" are "e to
re!olve th*! roblem8
Exception Handling
he rea!on the above e%amle *! !uch a roblem *! that the normal C(( 'unct*on9call9and9return !&!tem
!*ml& *!n$t robu!t enou)h to commun*cate error! bac to the call*n) 'unct*on- o re!olve th*! roblem,
C(( rov*de! lan)ua)e !uort 'or an error me!!a)*n) !&!tem called exception handling that comletel& b&a!!e! 'unct*on9call9and9return- +' an error occur! *n!*de a 'unct*on, rather than return*n) a value, &ou
can reort the roblem called an exception4 to the e%cet*on handl*n) !&!tem to automat*call& um to
the roer error9handl*n) code-
he C(( e%cet*on handl*n) !&!tem *! broen *nto three art! tr- bloc!, catc1 bloc!, and t1ro4
!tatement!- tr- bloc! are !*ml& re)*on! o' code "here &ou *n'orm the C(( com*ler that a runt*me
e%cet*on m*)ht occur- o declare a tr- bloc, &ou !*ml& "r*te the e&"ord tr-, then !urround the
aror*ate code *n curl& brace!- For e%amle, the 'ollo"*n) code !ho"! o'' a tr- bloc
8/9/2019 Advanced C++ Topics
3/12
tr-{ cout
8/9/2019 Advanced C++ Topics
4/12
"hat t&e o' obect "e !hould thro"- h*le "e can choo!e "hatever t&e o' obect "e$d l*e, C((
rov*de! a header '*le,
8/9/2019 Advanced C++ Topics
5/12
$eri9e2& $eri9e2BBoperator = (const $eri9e2 &ot1er){ if(t1is 8= &ot1er) { clear(); AaseBBoperator =(ot1er); cop-t1er(ot1er); } return /t1is;}
@ormall&, th*! code !hould "or "*thout roblem!, but "hen &ou add e%cet*on handl*n) to the m*% th*!
code *! *ncred*bl& dan)erou!- S*nce the code ma& thro" an e%cet*on at an& o*nt, there$! no "a& o'no"*n) that the ent*re bod& o' the if !tatement "*ll e%ecute- +n 'act, a er'ectl& val*d run o' th*! code
m*)ht be 'or the clear command to e%ecute but have the AaseBBoperator = 'unct*on thro" an
e%cet*on- +n th*! ca!e, "e have a !er*ou! roblem, !*nce "e$ve cleared out the obect "*thout relac*n) *t
"*th an& mean*n)'ul data- ! a re!ult, later *n our ro)ram, *' "e tr& to u!e the mal'ormed obect, "e$ll
robabl& )et runt*me error!- Clearl&, th*! *! a roblem-A
+' "e ma*nta*n the mental*t& that an& *ece o' code can thro" an e%cet*on at an& o*nt, *t "ould bev*rtuall& *mo!!*ble to "r*te e%cet*on9!a'e code- Ho"ever, *t$! much ea!*er *' "e could !omeho" mae
a!!umt*on! about "hat !ort! o' 'unct*on! "*ll and "*ll not thro" e%cet*on!- C(( ro'e!!*onal! tend to
cate)or*=e C(( code *nto three cla!!e! ba!ed on the*r relat*ve !a'et& "hen m*%ed "*th e%cet*on! ba!*ce%cet*on9!a'e code, !tron) e%cet*on9!a'e code, and nothro" e%cet*on9!a'e code- Basic exception-safe
code *! code that *! m*n*mall& e%cet*on9!a'e, mean*n) that *' an e%cet*on abort! *t m*d"a& throu)h
e%ecut*on, the obect *! not corruted- @ote that th*! doe! not mean that the obect *! *n *t! or*)*nal !tate,
onl& that *t$! not corruted- Strong exception-safe code rom*!e! that an& e%cet*on! at runt*me "*ll leave
the ro)ram !tate unchan)ed- hat *!, an& data e%*!t*n) be'ore the 'unct*on call "*ll rema*n that "a& even
*' 'unct*on 'lo" abort! m*d"a&- F*nall&, nothrow exception-safe code *! code that )uarantee! *t "*ll not
thro" an& e%cet*on! and that *' *t doe!, *t *! a !er*ou! error that !hould !hut do"n the ro)ram
*mmed*atel&-
r*t*n) code that meet! even the "eae!t o' the!e )uarantee! can be *ncred*bl& d*''*cult, and *ndeed
"r*t*n) e%cet*on9!a'e code *! one o' the mo!t challen)*n) a!ect! o' ro'e!!*onal C((- e$ve *)nored
e%cet*on handl*n) *n both CS106E and CS106L 'or th*! ver& rea!on *t )reatl& coml*cate! even the
!*mle!t o' ta!!- @onethele!!, e%cet*on handl*n) *! *ncred*bl& u!e'ul and *! deel& embedded *nto C((-
o learn more about "r*t*n) e%cet*on9!a'e code, &ou !hould be !ure to con!ult a re'erence-
#b$ect %emor %anagement and &AII
C(($! memor& model *! be!t de!cr*bed a! ;dan)erou!l& e''*c*ent-< nl*e other lan)ua)e! l*e ?ava, C((doe! not have a ;)arba)e collector< and con!e/uentl& &ou mu!t manuall& allocate and deallocate
memor&- t '*r!t, th*! m*)ht !eem l*e a !*mle ta! u!t 2elete an&th*n) &ou allocate "*th ne4, and
mae !ure not to 2elete !ometh*n) t"*ce- Ho"ever, *t can be /u*te d*''*cult to ee trac o' all o' the o*nter! &ou$ve allocated *n a ro)ram- 'ter all, &ou robabl& "on$t not*ce an& !&mtom! o' memor&
lea! unle!! &ou run &our ro)ram! 'or hour! on end, and *n all robabl& "*ll have to u!e a !ec*al tool to
chec memor& u!a)e- >ou can al!o run *nto trouble "here t"o cla!!e! each have a o*nter to a !hared
A +n 'act, *t$! !uch a !er*ou! roblem that *n !ome ca!e! &ou have to rad*call& re!tructure &our code to mae !ure *t$!
e%cet*on9!a'e- r*t*n) e%cet*on9!a'e a!!*)nment oerator! *! one !uch challen)e, and one o' the onl& val*d
"a&! to mae an e%cet*on9!a'e a!!*)nment oerator *! to !"*tch to another !trate)& called ;co&9and9!"a< to
er'orm the a!!*)nment- Con!ult a re'erence 'or more *n'ormat*on on co&9and9!"a-
8/9/2019 Advanced C++ Topics
6/12
obect- +' one o' the cla!!e! *!n$t care'ul and acc*dentall& 2elete! the memor& "h*le the other one *! !t*ll
acce!!*n) *t, &ou can )et !ome art*cularl& na!t& runt*me error! "here !eem*n)l& val*d data ha! been
corruted- he !*tuat*on )et! all the more coml*cated "hen &ou *ntroduce e%cet*on9handl*n) *nto them*%, "here the code to 2elete allocated memor& m*)ht not be reached becau!e o' a runt*me e%cet*on
!omet*me earl*er *n the code-
+n !ome ca!e! hav*n) a h*)h de)ree o' control over memor& mana)ement can be /u*te a boon to &our ro)ramm*n), but mo!t o' the t*me *t$! !*ml& a ha!!le- hat *' "e could !omeho" )et C(( to mana)e
our memor& 'or u!8 h*le bu*ld*n) a 'ull&9'unct*onal )arba)e collect*on !&!tem *n C(( "ould be u!t
!hort o' *mo!!*ble, u!*n) onl& ba!*c C(( concet! *t$! o!!*ble to con!truct an e%cellent aro%*mat*on o'
automat*c memor& mana)ement- he tr*c *! to bu*ld smart pointers, obect! "ho!e con!tructor! ac/u*re
a re!ource allocated b& ne4 and "ho!e de!tructor! clean u that re!ource throu)h a call to 2elete- hat
*!, "hen the obect! are con!tructed, the& "ra a ne"l&9allocated o*nter *n!*de an obect !hell that clean!u the me!! "hen the obect )oe! out o' !coe- Comb*ned "*th 'eature! l*e oerator overload*n), *t$!
o!!*ble to create !l*c !mart o*nter! that loo almo!t e%actl& l*e true C(( o*nter!, but that no" "hen
to 'ree unu!ed memor&-
he C(( Standard L*brar& e%ort! the auto%ptr t&e, a !mart o*nter that accet! *n *t! con!tructor a
o*nter to d&nam*call&9allocated memor& and "ho!e con!tructor call! 2elete on the re!ource-A auto%ptr *! a temlate cla!! "ho!e temlate arameter *nd*cate! "hat t&e o' obect the auto%ptr "*ll
;o*nt< at- For e%amle, an auto%ptr
8/9/2019 Advanced C++ Topics
7/12
to "orr& about the content! o' an auto%ptr be*n) cleaned u out 'rom underneath &ou b& another
auto%ptr to that re!ource- Second, *t mean! that *t$! !a'e to return auto%ptr! 'rom 'unct*on! "*thout
the re!ource )ett*n) cleaned u- hen return*n) an auto%ptr 'rom a 'unct*on, the or*)*nal co& o' the
auto%ptr "*ll tran!'er o"ner!h* to the ne" auto%ptr dur*n) return9value *n*t*al*=at*on, and the
re!ource "*ll be tran!'erred !a'el&-
! a con!e/uence o' the ;auto%ptr a!!*)nment *! tran!'erence< ol*c&, &ou mu!t be care'ul "hen
a!!*n) an auto%ptr b& value to a 'unct*on- S*nce the arameter "*ll be *n*t*al*=ed to the or*)*nal obect,
*t "*ll emt& the or*)*nal auto%ptr- S*m*larl&, &ou !hould not !tore auto%ptr! *n SL conta*ner!,
!*nce "hen the conta*ner! reallocate or balance them!elve! beh*nd the !cene! the& m*)ht a!!*)n
auto%ptr! around *n a "a& that "*ll tr*))er the obect de!tructor!-
For re'erence, here$! a l*!t o' the member 'unct*on! o' the auto%ptr temlate cla!!
auto%ptr (*-pe /resource) auto%ptr
8/9/2019 Advanced C++ Topics
8/12
'*le acce!! throu)h the old9!t&le I#E / !&!tem, &ou$d need to mae !ure to manuall& !et u and clean u
the '*le handle!- +n 'act, the !&!tem o' hav*n) obect! mana)e re!ource! throu)h the*r con!tructor! and
de!tructor! *! commonl& re'erred to a! resource acquisition is initialization, or !*ml& :++-
Exceptions and Smart Pointers
to th*! o*nt, !mart o*nter! m*)ht !eem l*e a cur*o!*t&, or erha! a u!e'ul con!truct *n a l*m*tednumber o' c*rcum!tance!- Ho"ever, "hen &ou *ntroduce e%cet*on handl*n) to the m*%, !mart o*nter!
"*ll be *nvaluable- +n 'act, *n ro'e!!*onal code "here e%cet*on! can be thro"n at almo!t an& o*nt,
!mart o*nter! have all but relaced re)ular C(( o*nter!-
Con!*der the 'ollo"*n) 'unct*on
int E9aluateE@pression(const string &e@pression){ ./ "ssume arseE@pression returns 2-namicall-?allocate2 memor- /. E@pression /e = arseE@pression(e@pression); int result = e?:e9aluate(); 2elete e; return result;}
@oth*n) *n th*! code !eem! all that out9o'9the9ord*nar&, and *t !eem! l*e *t "on$t lea an& re!ource! !*nce
the d&nam*call&9allocated memor& returned b& arseE@pression "*ll be cleaned u b& the call to
2elete e- n'ortunatel&, the above code *! a ver*table rec*e 'or d*!a!ter- 'ter all, "hat haen! *'
e?:e9aluate() thro"! an e%cet*on8 +' !o, control brea! out o' the 'unct*on be'ore the call to
2elete e, and the memor& "*ll be orhaned- o '*% th*! roblem, "e can relace the re)ular
E@pression / o*nter "*th an auto%ptr
8/9/2019 Advanced C++ Topics
9/12
class '-Class{ pu3licB '-Class() { t1ro4 0; .. *1ro4 an ar3itrar- e@ception } J'-Class() { cout
8/9/2019 Advanced C++ Topics
10/12
hat C(( doe!n$t *nvoe de!tructor! 'or *ncomletel&9'ormed obect! can be a )reat !ource o' trouble
"hen "or*n) "*th o*nter!- For e%amle, con!*der the 'ollo"*n) *mlementat*on o' a
Ainar-*reeNo2e cla!!
class Ainar-*reeNo2e{
pu3licB Ainar-*reeNo2e(Ainar-*reeNo2e /left, Ainar-*reeNo2e /rig1t) B leftC1il2(left), rig1tC1il2(rig1t) { ./ nitialiKation co2e /. } JAinar-*reeNo2e() { 2elete leftC1il2; 2elete rig1tC1il2; } ./ t1er mem3er functions /. pri9ateB Ainar-*reeNo2e /leftC1il2, /rig1tC1il2;};
+' the *n*t*al*=at*on code *n Ainar-*reeNo2e$! con!tructor thro"! an e%cet*on, then C(( "*ll not
*nvoe the Ainar-*reeNo2e de!tructor, but "*ll *n!tead call the de'ault de!tructor! 'or each o' the
ch*ldren- Ho"ever, !*nce the ch*ldren are o*nter!, there is no de'ault de!truct*on code, !o *' leftC1il2
and rig1tC1il2 o*nt to d&nam*call&9allocated memor&, the memor& "*ll !*ml& be lo!t- o re!olve
th*! roblem, "e can chan)e leftC1il2 and rig1tC1il2 'rom !*mle o*nter! *nto !mart o*nter!-
hat "a&, *' the con!tructor thro"! an e%cet*on, the !mart o*nter de!tructor! can clean u an& le'tover
memor&- h*! ha! the added advanta)e that "e don$t have to "orr& about 'or)ett*n) to clean u there!ource! *n the de!tructor- he ne", e%cet*on9!a'e code thu! loo! l*e th*!
class Ainar-*reeNo2e{ pu3licB Ainar-*reeNo2e(Ainar-*reeNo2e /left, Ainar-*reeNo2e /rig1t) B leftC1il2(left), rig1tC1il2(rig1t) { ./ nitialiKation co2e /. }
./ No 2estructor /. pri9ateB auto%ptr
8/9/2019 Advanced C++ Topics
11/12
%ore to Explore
h*! handout ha! barel& !cratched the !ur'ace o' e%cet*on handl*n) and !mart o*nter!, !o be !ure to
con!ult a re'erence 'or more *n'ormat*on- Here are !ome *ntere!t*n) to*c! to e%lore to )et &ou !tarted
1- T"e 'oost Smart Pointers h*le auto%ptr *! u!e'ul *n a "*de var*et& o' c*rcum!tance!, *n
man& a!ect! *t *! l*m*ted- Onl& one auto%ptr can o*nt to a re!ource at a t*me, and auto%ptr!cannot be !tored *n!*de o' SL conta*ner!- he oo!t C(( l*brar*e! con!e/uentl& rov*de a hu)e
number o' !mart o*nter!, man& o' "h*ch emlo& con!*derabl& more coml*cated re!ource9
mana)ement !&!tem! than auto%ptr- S*nce man& o' the!e !mart o*nter! are l*el& to be
*ncluded *n the ne%t rev*!*on o' the C(( !tandard, &ou !hould be !ure to read *nto them-
2- T"e pImpl Idiom r*t*n) e%cet*on9!a'e co& con!tructor! and a!!*)nment oerator! *!
'ru!trat*n)l& d*''*cult, and one !olut*on to the roblem *! to u!e the pImpl idiom- +ml !tand! 'or;o*nter to *mlementat*on,< and mean! that rather than hav*n) a cla!! have actual data member!,
*n!tead *t ha! a !mart o*nter to an ;*mlementat*on obect< that conta*n! all o' the cla!! data-
+ml al!o can be u!ed to reduce com*le t*me! *n lar)e roect!- S*nce *t ar*!e! !o 're/uentl& *n
ro'e!!*onal code, &ou !hould certa*nl& loo *nto +ml *' &ou lan on !er*ou!l& ur!u*n) C((-
3- Exception Specifications >ou can e%l*c*tl& mar "hat t&e! o' e%cet*on! C(( 'unct*on! are
le)all& allo"ed to thro"- h*le th*! *ntroduce! a b*t o' overhead *nto &our ro)ram, e%cet*on!ec*'*cat*on! can )reatl& reduce the number o' bu)! *n &our code b& *dent*'&*n) atche! o'
e%cet*on !a'et& *n an other"*!e uncerta*n "orld-
- (ot"ro! new he normal C(( ne4 oerator thro"! a 3a2%alloc e%cet*on *' *t *! unable to
obta*n the needed amount o' memor&- +n ca!e th*! *!n$t "hat &ou "ant, &ou can u!e the nothrow
new , a ver!*on o' the ne4 oerator that cannot thro" e%cet*on!- he !&nta% *!
ne4 (not1ro4) DataType-
5- assert Funct*on! l*e the CS106 Error that halt e%ecut*on at runt*me are !ome"hat *nele)ant
becau!e the& don$t )*ve &our ro)ram a chance to re!ond to an error- Ho"ever, "hen de!*)n*n)
and te!t*n) !o't"are, Error9l*e 'unct*on! can be u!e'ul to *no*nt the !ot! "here error! occur
*n &our code- For th*! uro!e, C(( *nher*t! the C assert macro, "h*ch evaluate! an e%re!!*on
and halt! e%ecut*on *' the value *! 'al!e- Ho"ever, unl*e Error, "hen com*l*n) the ro)ram *n
relea!e mode, assert *! d*!abled, !o &ou can !moe out bu)! dur*n) debu) develoment, then
leave error9handl*n) *n relea!e mode to the e%cet*on9handl*n) !&!tem- assert *! e%orted b&
the
8/9/2019 Advanced C++ Topics
12/12
)inal T"oug"ts
+t$! been /u*te a tr* !*nce "e '*r!t !tarted "*th the +OStream l*brar& almo!t three month! a)o- >ou no"
no" ho" to ro)ram "*th the SL, "r*te "ell9behaved C(( obect!, and even *mlement 'unct*onal
ro)ramm*n) con!truct! *n!*de the other"*!e *merat*veBobect9or*ented C(( lan)ua)e- ut de!*te the*mmen!e volume o' mater*al "e$ve covered th*! /uarter, CS106L *! onl& the t* o' the *ceber) "hen *t
come! to C((- here are volume! o' art*cle! and boo! out there that cover all !ort! o' ama=*n) t*! andtr*c! "hen *t come! to C((, and b& ta*n) the *n*t*at*ve and e%lor*n) "hat$! out there &ou can hone &our
C(( !*ll! unt*l roblem !olv*n) *n C(( tran!'orm! 'rom ;ho" do + !olve th*! roblem8< to ;"h*ch o'
the!e man& ot*on! *! be!t 'or !olv*n) th*! roblem8<
C(( *! an ama=*n) and beaut*'ul lan)ua)e- +t ha! !ome o' the mo!t e%re!!*ve !&nta% o' an& modern
ro)ramm*n) lan)ua)e, and a''ord! an enormou! lat*tude *n ro)ramm*n) !t&le!- O' cour!e, *t ha! *t!
'la"!, a! cr*t*c! are ea)er to o*nt out, but *t *! unden*able that C(( *! an *ncred*bl& *mortant and u!e'ul
lan)ua)e *n the modern ro)ramm*n) a)e-
+ hoe that &ou$ve eno&ed CS106L a! much a! + have- h*! cla!! ha! been a b*) e%er*ment, and + hoe
that &ou$re !at*!'*ed "*th the re!ult!- e$ll be o''er*n) the cla!! a)a*n ne%t /uarter, !o &ou ma& be the '*r!t
cla!! *n a ne" Stan'ord comuter !c*ence trad*t*onI
Have 'un "*th C((, and b& all mean!, *' &ou ever have an& /ue!t*on!, 'eel 'ree to ema*l me-
.no&I