Tải bản đầy đủ - 0 (trang)
Chapter 2. Introduction to C++ and the Standard Library

Chapter 2. Introduction to C++ and the Standard Library

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

Chapter2.IntroductiontoC++andthe

StandardLibrary

2.1History

2.2NewLanguageFeatures

2.3ComplexityandtheBig-ONotation



2.1History

ThestandardizationofC++wasstartedin1989andfinishedattheendof

1997,althoughsomeformalmotionsdelayedthefinalpublicationuntil

September1998.Theresultwasareferencemanualwithapproximately

750pages,publishedbytheInternationalStandardsOrganization(ISO).

Thestandardhasthetitle"InformationTechnology—Programming

Languages—C++."ItsdocumentnumberisISO/IEC14882-1998,andit

isdistributedbythenationalbodiesoftheISO,suchastheANSIinthe

UnitedStates.[1]

ThestandardwasanimportantmilestoneforC++.Becauseitdefinesthe

exactcontentsandbehaviorofC++,itmakesiteasiertoteachC++,to

useC++inapplications,andtoportC++programstodifferentplatforms.

ItalsogivesusersgreaterfreedomofchoiceregardingdifferentC++

implementations.Itsstabilityandportabilityhelplibraryprovidersandtool

providersaswellasimplementers.Thus,thestandardhelpsC++

applicationdevelopersbuildbetterapplicationsfaster,andmaintainthem

withlesscostandeffort.

Partofthestandardisastandardlibrary.Thislibraryprovidescore

componentsforI/O,strings,containers(datastructures),algorithms

(suchassort,search,andmerge),supportfornumericcomputation,and

(ascouldbeexpectedfromaninternationalstandard)supportfor

internationalization(suchasdifferentcharactersets).

Youmaywonderwhythestandardizationprocesstookalmost10years,

andifyouknowsomedetailsaboutthestandardyoumightwonderwhy



afterallthistimeitisstillnotperfect.Tenyears,infact,wasnotenough

time!Although,accordingtothehistoryandthecontextofthe

standardizationprocess,alotwasaccomplished.Theresultisusablein

practice,butitisnotperfect(nothingeveris).

Thestandardisnottheresultofacompanywithabigbudgetandalotof

time.Standardsorganizationspaynothingoralmostnothingtothe

peoplewhoworkondevelopingstandards.So,ifaparticipantdoesn't

workforacompanythathasaspecialinterestinthestandard,thework

isdoneforfun.Thankgoodnesstherewerealotofdedicatedpeople

whohadthetimeandthemoneytodojustthat.

TheC++standardwasnotdevelopedfromscratch.Itwasbasedonthe

languageasdescribedbyBjarneStroustrup,thecreatorofC++.The

standardlibrary,however,wasnotbasedonabookoronanexisting

library.Instead,different,existingclasseswereintegrated.[2]Thus,the

resultisnotveryhomogeneous.Youwillfinddifferentdesignprinciples

fordifferentcomponents.Agoodexampleisthedifferencebetweenthe

stringclassandtheSTL,whichisaframeworkfordatastructuresand

algorithms:

Stringclassesaredesignedasasafeandconvenientcomponent.

Thus,theyprovideanalmostself-explanatoryinterfaceandcheck

formanyerrorsintheinterface.

TheSTLwasdesignedtocombinedifferentdatastructureswith

differentalgorithmswhileachievingthebestperformance.Thus,the

STLisnotveryconvenientanditisnotrequiredtocheckformany

logicalerrors.Tobenefitfromthepowerfulframeworkandgreat

performanceoftheSTL,youmustknowtheconceptsandapply

themcarefully.

Bothofthesecomponentsarepartofthesamelibrary.Theywere

harmonizedabit,buttheystillfollowtheirindividual,fundamentaldesign

philosophies.

Onecomponentofthelibraryexistedasadefactostandardbefore

standardizationbegan:theIOStreamlibrary.Developedin1984,itwas

reimplementedandpartiallyredesignedin1989.Becausemany



programswereusingitalready,thegeneralconceptoftheIOStream

librarywasnotchanged,thuskeepingitbackwardcompatible.

Ingeneral,thewholestandard(languageandlibrary)istheresultofalot

ofdiscussionsandinfluencefromhundredsofpeopleallovertheworld.

Forexample,theJapanesecameupwithimportantsupportfor

internationalization.Ofcourse,mistakesweremade,mindswere

changed,andpeoplehaddifferentopinions.Then,in1994,whenpeople

thoughtthestandardwasclosetobeingfinished,theSTLwas

incorporated,whichchangedthewholelibraryradically.However,toget

finished,thethinkingaboutmajorextensionswaseventuallystopped,

regardlessofhowusefultheextensionwouldbe.Thus,hashtablesare

notpartofthestandard,althoughtheyshouldbeapartoftheSTLasa

commondatastructure.

Thecurrentstandardisnottheendoftheroad.Therewillbefixesof

bugsandinconsistencies,andtherelikelywillbeanextversionofthe

standardinfiveyearsorso.Howeverforthenextfewyears,C++

programmershaveastandardandthechancetowritepowerfulcodethat

isportabletoverydifferentplatforms.



2.2NewLanguageFeatures

ThecorelanguageandthelibraryofC++werestandardizedinparallel.

Inthisway,thelibrarycouldbenefitfromimprovementsinthelanguage

andthelanguagecouldbenefitfromexperiencesoflibrary

implementation.Infact,duringthestandardizationprocessthelibrary

oftenusedspeciallanguagefeaturesthatwerenotyetavailable.

C++isnotthesamelanguageitwasfiveyearsago.Ifyoudidn'tfollowits

evolution,youmaybesurprisedwiththenewlanguagefeaturesusedby

thelibrary.Thissectiongivesyouabriefoverviewofthosenewfeatures.

Fordetails,refertobooksonthelanguageinquestion.

WhileIwaswritingthisbook(in1998),notallcompilerswereableto

provideallofthenewlanguagefeatures.Ihope(andexpect)thatthiswill

changeverysoon(mostcompilervendorswerepartofthe

standardizationprocess).Thus,youmayberestrictedinyouruseofthe



library.Portableimplementationsofthelibrarytypicallyconsiderwhether

featuresarepresentintheenvironmenttheyuse(theyusuallyhave

sometestprogramstocheckwhichlanguagefeaturesarepresent,and

thensetpreprocessordirectivesaccordingtotheresultofthecheck).I'll

mentionanyrestrictionsthataretypicalandimportantthroughoutthe

bookbyusingfootnotes.

Thefollowingsubsectionsdescribethemostimportantnewlanguage

featuresthatarerelevantfortheC++standardlibrary.



2.2.1Templates

Almostallpartsofthelibraryarewrittenastemplates.Withouttemplate

support,youcan'tusethestandardlibrary.Moreover,thelibraryneeded

newspecialtemplatefeatures,whichIintroduceafterashortoverviewof

templates.

Templatesarefunctionsorclassesthatarewrittenforoneormoretypes

notyetspecified.Whenyouuseatemplate,youpassthetypesas

arguments,explicitlyorimplicitly.Thefollowingisatypicalexample—a

functionthatreturnsthemaximumoftwovalues:



template

inlineconstT&max(constT&a,constT&b)

{

//ifa
returna
}

Here,thefirstlinedefinesTasanarbitrarydatatypethatisspecifiedby

thecallerwhenthecallercallsthefunction.Youcanuseanyidentifieras

aparametername,butusingTisverycommon,ifnotadefacto

convention.Thetypeisclassifiedbyclass,althoughitdoesnothave

tobeaclass.Youcanuseanydatatypeaslongasitprovidesthe

operationsthatthetemplateuses.[3]



Followingthesameprinciple,youcan"parameterize"classesonarbitrary

types.Thisisusefulforcontainerclasses.Youcanimplementthe

containeroperationsforanarbitraryelementtype.TheC++standard

libraryprovidesmanytemplatecontainerclasses(forexample,see

Chapter6orChapter10).Italsousestemplateclassesformanyother

reasons.Forexample,thestringclassesareparameterizedonthetype

ofthecharactersandthepropertiesofthecharacterset(seeChapter

11).

Atemplateisnotcompiledoncetogeneratecodeusableforanytype;

instead,itiscompiledforeachtypeorcombinationoftypesforwhichitis

used.Thisleadstoanimportantprobleminthehandlingoftemplatesin

practice:Youmusthavetheimplementationofatemplatefunction

availablewhenyoucallit,sothatyoucancompilethefunctionforyour

specifictype.Therefore,theonlyportablewayofusingtemplatesatthe

momentistoimplementtheminheaderfilesbyusinginlinefunctions.[4]

ThefullfunctionalityoftheC++standardlibraryrequiresnotonlythe

supportoftemplatesingeneral,butalsomanynewstandardized

templatefeatures,includingthosediscussedinthefollowingparagraphs.

NontypeTemplateParameters

Inadditiontotypeparameters,itisalsopossibletousenontype

parameters.Anontypeparameteristhenconsideredaspartofthetype.

Forexample,forthestandardclassbitset<>(classbitset<>is

introducedinSection10.4,)youcanpassthenumberofbitsasthe

templateargument.Thefollowingstatementsdefinetwobitfields,one

with32bitsandonewith50bits:



bitset<32>fIags32;//bitsetwith32bits

bitset<50>flags50;//bitsetwith50bits

Thesebitsetshavedifferenttypesbecausetheyusedifferenttemplate

arguments.Thus,youcan'tassignorcomparethem(exceptifa

correspondingtypeconversionisprovided).



DefaultTemplateParameters

Templatesclassesmayhavedefaultarguments.Forexample,the

followingdeclarationallowsonetodeclareobjectsofclassMyClass

withoneortwotemplatearguments[5]:



template>

classMyClass;

Ifyoupassonlyoneargument,thedefaultparameterisusedassecond

argument:



MyClassx1;//equivalentto:MyClass<

Notethatdefaulttemplateargumentsmaybedefinedintermsof

previousarguments.

Keywordtypename

Thekeywordtypenamewasintroducedtospecifythattheidentifier

thatfollowsisatype.Considerthefollowingexample:



template

ClassMyClass{

typenameT::SubType*ptr;

...

};

Here,typenameisusedtoclarifythatSubTypeisatypeofclassT.

Thus,ptrisapointertothetypeT::SubType.Without

typename,SubTypewouldbeconsideredastaticmember.Thus



T::SubType*ptr



wouldbeamultiplicationofvalueSubTypeoftypeTwithptr.

AccordingtothequalificationofSubTypebeingatype,anytypethatis

usedinplaceofTmustprovideaninnertypeSubType.Forexample,

theuseoftypeQasatemplateargument



MyClassx;

ispossibleonlyiftypeQhasaninnertypedefinitionsuchasthe

following:



classQ{

typedefintSubType;

...

};

Inthiscase,theptrmemberofMyClasswouldbeapointerto

typeint.However,thesubtypecouldalsobeanabstractdatatype

(suchasaclass):



classQ{

classSubType;

...

};

Notethattypenameisalwaysnecessarytoqualifyanidentifierofa

templateasbeingatype,evenifaninterpretationthatisnotatypewould

makenosense.Thus,thegeneralruleinC++isthatanyidentifierofa

templateisconsideredtobeavalue,exceptitisqualifiedby



typename.

Apartfromthis,typenamecanalsobeusedinsteadofclassina

templatedeclaration:



templateclassMyClass;



MemberTemplates

Memberfunctionsofclassesmaybetemplates.However,member

templatesmaynotbevirtual,normaytheyhavedefaultparameters.For

example:



classMyClass{

...

template

voidf(T);

};

Here,MyClass::fdeclaresasetofmemberfunctionsforparameters

ofanytype.Youcanpassanyargumentaslongasitstypeprovidesall

operationsusedbyf().

Thisfeatureisoftenusedtosupportautomatictypeconversionsfor

membersintemplateclasses.Forexample,inthefollowingdefinitionthe

argumentxofassign()musthaveexactlythesametypeasthe

objectitiscalledfor:



template

classMyClass{

private:

Tvalue;

public:

voidassign(constMyClass&x){//xmusthav

value=x.value;

}

...

};

Itwouldbeanerrortousedifferenttemplatetypesfortheobjectsofthe

assign()operationevenifanautomatictypeconversionfromone

typetotheotherisprovided:



voidf()

{

MyClassd;

MyClassi;



d.assign(d);//OK

d.assign(i);//ERROR:iisMyClass

//butMyClass

}

Byprovidingadifferenttemplatetypeforthememberfunction,yourelax

theruleofexactmatch.Themembertemplatefunctionargumentmay

haveanytemplatetype,thenaslongasthetypesareassignable:



template

classMyClass{

private:

Tvalue;

public

template//membe

voidassign(constMyClass&x){//allow

value=x.getValue();

}

TgetValue()const{

returnvalue;

}

...

};



voidf()

{

MyClassd;



MyClassi;



d.assign(d);//OK

d.assign(i);//OK(intisassignableto

}

Notethattheargumentxofassign()nowdiffersfromthetypeof

*this.Thus,youcan'taccessprivateandprotectedmembersof

MyClass<>directly.Instead,youhavetousesomethinglike

getValue()inthisexample.

Aspecialformofamembertemplateisatemplateconstructor.Template

constructorsareusuallyprovidedtoenableimplicittypeconversions

whenobjectsarecopied.Notethatatemplateconstructordoesnothide

theimplicitcopyconstructor.Ifthetypematchesexactly,theimplicitcopy

constructorisgeneratedandcalled.Forexample:



template

classMyClass{

public:

//copyconstructorwithimplicittypeconversion

//-doesnothideimplicitcopyconstructor

template

MyClass(constMyClass&x);

...

};



voidf()

{

MyClassxd;

...

MyClassxd2(xd);//callsbuilt-inc

MyClassxi(xd);//callstemplatec



...

}

Here,thetypeofxd2isthesameasthetypeofxd,soitisinitialized

viathebuilt-incopyconstructor.Thetypeofxidiffersfromthetypeof

xd,soitisinitializedbyusingthetemplateconstructor.Thus,ifyou

writeatemplateconstructor,don'tforgettoprovideacopyconstructor,if

thedefaultcopyconstructordoesnotfityourneeds.SeeSection4.1,for

anotherexampleofmembertemplates.

NestedTemplateClasses

Nestedclassesmayalsobetemplates:



template

classMyClass{

...

template

classNestedClass;

...

};

2.2.2ExplicitInitializationforFundamentalTypes

Ifyouusethesyntaxofanexplicitconstructorcallwithoutarguments,

fundamentaltypesareinitializedwithzero:



inti1;//undefinedvalue

inti2=int();//initializedwithzero

Thisfeatureisprovidedtoenableyoutowritetemplatecodethatensures

thatvaluesofanytypehaveacertaindefaultvalue.Forexample,inthe

followingfunctiontheinitializationguaranteesthatxisinitializedwith

zeroforfundamentaltypes:



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

Chapter 2. Introduction to C++ and the Standard Library

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

×