22
Chapter1 Programming:AGeneralOverview
m
isuninitializedatthispoint.InC
++
,nosuch checkisperformed toverify that
m
is
assignedavaluepriortobeing used (however,severalvendors makeproductsthatdo
additionalchecks,includingthisone).Theuseofuninitializedpointerstypicallycrashes
programs,becausetheyresultinaccessofmemorylocationsthatdonotexist.Ingeneral,
itisagood ideatoprovidean initialvalue,eitherbycombining lines3 and 5,orby
initializing
m
tothe
nullptr
pointer.
DynamicObjectCreation
Line5illustrateshowobjectscanbecreateddynamically.InC
++
new
returnsapointer
tothenewlycreatedobject.InC
++
thereareseveralwaystocreateanobjectusingits
zero-parameterconstructor.Thefollowingwouldbelegal:
m = = new w IntCell( ( );
// OK
m = = new w IntCell{ { };
// C
++
11
m = = new w IntCell;
// Preferred d in this s text
Wegenerallyusethelastformbecauseoftheproblemillustratedby
obj4
inSection1.4.3.
GarbageCollectionanddelete
In somelanguages,when an object is nolongerreferenced,itissubjecttoautomatic
garbagecollection;theprogrammerdoesnothavetoworryaboutit.C
++
doesnothave
garbagecollection.When an objectthatisallocatedby
new
is nolongerreferenced,the
delete
operationmustbeappliedtotheobject(throughapointer).Otherwise,themem-
orythatitconsumesislost(untiltheprogramterminates).Thisisknownasamemory
leak. Memory y leaks are, , unfortunately, common n occurrences in many C
++
programs.
Fortunately,manysourcesofmemoryleakscanbeautomaticallyremovedwithcare.One
importantruleistonotuse
new
whenanautomaticvariablecanbeusedinstead.Inthe
originalprogram,the
IntCell
isnotallocatedby
new
butinsteadisallocatedasalocalvari-
able.Inthatcase,thememoryforthe
IntCell
isautomaticallyreclaimedwhenthefunction
inwhichitisdeclaredreturns.The
delete
operatorisillustratedatline9ofFigure1.11.
AssignmentandComparisonofPointers
AssignmentandcomparisonofpointervariablesinC
++
isbasedonthevalueofthepointer,
meaningthememoryaddressthatitstores.Thustwopointervariablesareequalifthey
pointatthesameobject.Iftheypointatdifferentobjects,thepointervariablesarenot
equal,eveniftheobjectsbeingpointedatarethemselvesequal.If
lhs
and
rhs
arepointer
variables(ofcompatibletypes),then
lhs=rhs
makes
lhs
pointatthesameobjectthat
rhs
pointsat.
4
AccessingMembersofanObjectthroughaPointer
Ifapointervariablepointsataclasstype,thena(visible)memberoftheobjectbeing
pointedat can beaccessed viathe
->
operator. Thisisillustratedat lines 6and d 7 of
Figure1.11.
4
Throughoutthistext,weuse
lhs
and
rhs
tosignifyleft-handsideandright-handsideofabinaryoperator.
How to add pdf to powerpoint slide - C# Create PDF from PowerPoint Library to convert pptx, ppt to PDF in C#.net, ASP.NET MVC, WinForms, WPF
Online C# Tutorial for Creating PDF from Microsoft PowerPoint Presentation
and paste pdf into powerpoint; how to change pdf to powerpoint slides
How to add pdf to powerpoint slide - VB.NET Create PDF from PowerPoint Library to convert pptx, ppt to PDF in vb.net, ASP.NET MVC, WinForms, WPF
VB.NET Tutorial for Export PDF file from Microsoft Office PowerPoint
how to add pdf to powerpoint slide; how to convert pdf to powerpoint slides
1.5 C
++
Details
23
Address-ofOperator(&)
Oneimportantoperatoris theaddress-of operator
&
.Thisoperatorreturnsthemem-
orylocationwhereanobjectresidesandisusefulforimplementinganaliastestthatis
discussedinSection1.5.6.
1.5.2 Lvalues,Rvalues,andReferences
Inadditiontopointertypes,C
++
definesreferencetypes.Oneofthemajorchangesin
C
++
11isthecreationofanewreferencetype,knownasanrvaluereference.Inorderto
discussrvaluereferences,andthemorestandardlvaluereference,weneedtodiscussthe
conceptoflvaluesandrvalues.Notethatthepreciserulesarecomplex,andweprovide
ageneraldescription ratherthanfocusingon thecornercases that areimportant in a
languagespecificationandforcompilerwriters.
An lvalue isanexpression thatidentifiesanon-temporaryobject.Anrvalueisan
expressionthatidentifiesatemporaryobjectorisavalue(suchasaliteralconstant)not
associatedwithanyobject.
Asexamples,considerthefollowing:
vector<string> arr( ( 3 );
const int t x x = 2;
int y;
...
int z z = x x + + y;
string str r = "foo";
vector<string> *ptr r = &arr;
With thesedeclarations,
arr
,
str
,
arr[x]
,
&x
,
y
,
z
,
ptr
,
*ptr
,
(*ptr)[x]
arealllvalues.
Additionally,
x
isalsoanlvalue,althoughitisnotamodifiablelvalue.Asageneralrule,if
youhaveanameforavariable,itisanlvalue,regardlessofwhetheritismodifiable.
Fortheabovedeclarations
2
,
"foo"
,
x+y
,
str.substr(0,1)
areallrvalues.
2
and
"foo"
are
rvaluesbecausetheyareliterals.Intuitively,
x+y
isanrvaluebecauseitsvalueistemporary;
itiscertainlynot
x
or
y
,butitisstoredsomewherepriortobeingassignedto
z
.Similar
logicappliesfor
str.substr(0,1)
.
Noticetheconsequencethattherearesomecasesinwhichtheresultofafunctioncall
oroperatorcallcanbeanlvalue(since
*ptr
and
arr[x]
generatelvalues)asdoes
cin>>x>>y
andotherswhereitcanbeanrvalue;hence,thelanguagesyntaxallowsafunctioncall
oroperatoroverloadtospecify this in thereturntype,and this aspectis discussed in
Section1.5.4.Intuitively,ifthefunctioncallcomputesanexpressionwhosevaluedoes
notexistpriortothecallanddoesnotexistoncethecallisfinishedunlessitiscopied
somewhere,itislikelytobeanrvalue.
Areferencetypeallowsustodefineanewnameforanexistingvalue.InclassicC++,a
referencecangenerallyonlybeanameforanlvalue,sincehavingareferencetoatemporary
wouldleadtotheabilitytoaccessanobjectthathastheoreticallybeendeclaredasnolonger
needed,andthusmayhavehaditsresourcesreclaimedforanotherobject.However,in
C
++
11,wecanhavetwotypesofreferences:lvaluereferencesandrvaluereferences.
VB.NET PowerPoint: Read, Edit and Process PPTX File
How to convert PowerPoint to PDF, render PowerPoint to and effective VB.NET solution to add desired watermark on source PowerPoint slide at specified
how to change pdf file to powerpoint; how to convert pdf to ppt for
VB.NET PowerPoint: Process & Manipulate PPT (.pptx) Slide(s)
& editing library SDK, this VB.NET PowerPoint processing control add-on can to provide powerful & profession imaging controls, PDF document, image
pdf to powerpoint converter online; convert pdf to editable powerpoint online
24
Chapter1 Programming:AGeneralOverview
InC
++
11,anlvaluereferenceisdeclaredbyplacingan
&
aftersometype.Anlvalue
referencethenbecomesasynonym(i.e.,anothername)fortheobjectitreferences.For
instance,
string str = "hell";
string & rstr = str;
// rstr r is another r name e for str
rstr += = ’o’;
// changes s str to "hello"
bool cond = (&str == &rstr);
// true; ; str and rstr are e same e object
string & bad1 = "hello";
// illegal: : "hello" is not a modifiable e lvalue
string & bad2 = str + "";
// illegal: : str+"" " is s not t an n lvalue
string & sub = str.substr( 0, 4 ); // / illegal: : str.substr( 0, 4 ) is not an lvalue
InC
++
11,anrvaluereferenceisdeclaredbyplacingan
&&
aftersometype.Anrvalue
referencehasthesamecharacteristicsasanlvaluereferenceexceptthat,unlikeanlvalue
reference,anrvaluereferencecanalsoreferenceanrvalue(i.e.,atemporary).Forinstance,
string str = "hell";
string && bad1 = = "hello";
// Legal
string && bad2 = = str r + + "";
// Legal
string && sub = str.substr( ( 0, 4 4 ); // / Legal
WhereaslvaluereferenceshaveseveralclearusesinC
++
,theutilityofrvaluereferencesis
notobvious.Severalusesoflvaluereferenceswillbediscussednow;rvaluereferencesare
deferreduntilSection1.5.3.
lvaluereferencesuse#1:aliasingcomplicatednames
Thesimplestuse,whichwewillseeinChapter5,istousealocalreferencevariablesolely
forthepurposeofrenaminganobjectthatisknownbyacomplicatedexpression.The
codewewillseeissimilartothefollowing:
auto & whichList t = = theLists[ myhash( x, theLists.size( ( ) ) ) ];
if( find( ( begin( ( whichList t ), end( whichList ), x x ) ) != end( whichList ) ) )
return false;
whichList.push_back( x x );
A reference e variable e is s used so o that the considerably more complex expression
theLists[myhash(x,theLists.size())]
doesnothavetobewritten(andthenevaluated)four
times.Simplywriting
auto whichList = = theLists[ [ myhash( x, theLists.size( ( ) ) ) ];
wouldnotwork;itwouldcreateacopy,andthenthe
push_back
operationonthelastline
wouldbeappliedtothecopy,nottheoriginal.
lvaluereferencesuse#2:rangeforloops
Aseconduseisintherange
for
statement.Supposewewouldliketoincrementby1all
valuesina
vector
.Thisiseasywitha
for
loop:
for( int t i i = 0; i < < arr.size( ( ); ++i )
++arr[ i ];
C# PowerPoint - How to Process PowerPoint
With our C#.NET PowerPoint control, developers are able to split a PowerPoint into two or more small files. Add & Insert PowerPoint Page/Slide in C#.
convert pdf into ppt; how to convert pdf into powerpoint presentation
VB.NET PowerPoint: Edit PowerPoint Slide; Insert, Add or Delete
NET PowerPoint slide modifying control add-on enables view more VB.NET PowerPoint slide processing functions & profession imaging controls, PDF document, image
how to convert pdf file to powerpoint presentation; how to change pdf to powerpoint
1.5 C
++
Details
25
Butofcourse,arange
for
loopwouldbemoreelegant.Unfortunately,thenaturalcode
doesnotwork,because
x
assumesacopyofeachvalueinthe
vector
.
for( auto o x x : arr r )
// broken
++x;
Whatwereallywantisfor
x
tobeanothernameforeachvalueinthe
vector
,whichiseasy
todoif
x
isareference:
for( auto o & & x : arr ) // works
++x;
lvaluereferencesuse#3:avoidingacopy
Supposewehaveafunction
findMax
thatreturnsthelargestvalueina
vector
orotherlarge
collection.Thengivena
vectorarr
,ifweinvoke
findMax
,wewouldnaturallywrite
auto x x = = findMax( ( arr r );
However,noticethatifthe
vector
storeslargeobjects,thentheresultisthat
x
willbea
copy ofthelargestvaluein
arr
.Ifweneedacopyforsomereason,thatisfine;how-
ever,inmanyinstances,weonlyneedthevalueandwillnotmakeanychangesto
x
.In
suchacase,itwouldbemoreefficienttodeclarethat
x
isanothernameforthelargest
valuein
arr
,andhencewewoulddeclare
x
tobeareference(
auto
willdeduceconst-
ness;if
auto
isnotused,thentypicallyanon-modifiablereferenceisexplicitlystatedwith
const
):
auto & & x x = findMax( arr );
Normally,thismeansthat
findMax
wouldalsospecifyareturntypethatindicatesareference
variable(Section1.5.4).
Thiscodeillustratestwoimportantconcepts:
1. Reference variables are often used to avoid copying objects across function-call
boundaries(eitherinthefunctioncallorthefunctionreturn).
2. Syntax x is s needed d in function declarations s and returns to enable the passing and
returningusingreferencesinsteadofcopies.
1.5.3 ParameterPassing
Manylanguages,CandJavaincluded,passallparametersusingcall-by-value:theactual
argumentiscopiedintotheformalparameter.However,parametersinC
++
couldbelarge
complexobjectsforwhichcopyingisinefficient.Additionally,sometimesitisdesirable
tobeabletoalterthevaluebeingpassedin.Asaresultofthis,C
++
hashistoricallyhad
threedifferentwaystopassparameters,andC
++
11hasaddedafourth.Wewillbeginby
describingthethreeparameter-passingmechanismsinclassicC
++
andthenexplainthe
newparameter-passingmechanismthathasbeenrecentlyadded.
VB.NET PowerPoint: Read & Scan Barcode Image from PPT Slide
PDF-417 barcode scanning SDK to detect PDF-417 barcode How to customize VB.NET PowerPoint QR Code barcode scanning VB.NET PPT barcode scanner add-on to detect
embed pdf into powerpoint; convert pdf file to powerpoint online
VB.NET PowerPoint: Convert & Render PPT into PDF Document
to convert one certain PowerPoint slide or a specified range of slides into .pdf document format using this VB.NET PowerPoint to PDF conversion library add-on.
convert pdf back to powerpoint; chart from pdf to powerpoint
26
Chapter1 Programming:AGeneralOverview
Toseethereasonswhycall-by-valueisnotsufficientastheonlyparameter-passing
mechanisminC
++
,considerthethreefunctiondeclarationsbelow:
double average( ( double a, double b );
// returns s average e of f a and b
void swap( double a, double b b );
// swaps s a and b; wrong parameter types
string randomItem( ( vector<string> > arr ); // returns s a a random item m in arr; ; inefficient
average
illustratesanidealuseofcall-by-value.Ifwemakeacall
double z z = = average( ( x, y y );
then call-by-valuecopies
x
into
a
,
y
into
b
,andthen executesthecodeforthe
average
function definition that is fully y specified d elsewhere.Presuming that
x
and
y
arelocal
variablesinaccessibleto
average
,itisguaranteedthatwhen
average
returns,
x
and
y
are
unchanged,whichisaverydesirableproperty.However,thisdesirablepropertyisexactly
whycall-by-valuecannotworkfor
swap
.Ifwemakeacall
swap( x, , y y );
then call-by-valueguarantees thatregardlessofhow
swap
isimplemented,
x
and
y
will
remainunchanged.Whatweneedinsteadistodeclarethat
a
and
b
arereferences:
void swap( ( double e & a, double & b );
// swaps a and b; correct parameter types
Withthissignature,
a
isasynonymfor
x
,and
b
isasynonymfor
y
.Changesto
a
and
b
in
theimplementationof
swap
arethuschangesto
x
and
y
.Thisformofparameterpassing
hasalwaysbeenknownascall-by-referenceinC
++
.InC
++
11,thisismoretechnically
call-by-lvalue-reference,butwewillusecall-by-referencethroughoutthistexttoreferto
thisstyleofparameterpassing.
The second problem with call-by-value is illustrated in
randomItem
. This function
intendstoreturnarandomitemfromthe
vectorarr
;inprinciple,thisisaquickoperation
consistingofthegenerationofa“random”numberbetween0and
arr.size()-1
,inclusive,
inordertodetermineanarrayindexandthereturningoftheitematthisrandomlychosen
arrayindex.Butusingcall-by-valueastheparameter-passingmechanismforcesthecopy
ofthe
vectorvec
inthecall
randomItem(vec)
.Thisisatremendouslyexpensiveoperation
comparedtothecostofcomputingandreturningarandomlychosenarrayindexandis
completelyunnecessary.Normally,theonlyreasontomakeacopyistomakechangesto
thecopywhilepreservingtheoriginal.But
randomItem
doesn’tintendtomakeanychanges
atall;itisjustviewing
arr
.Thus,wecanavoidthecopybutachievethesamesemanticsby
declaringthat
arr
isaconstantreferenceto
vec
;asaresult,
arr
isasynonymfor
vec
,with
nocopy,butsinceitisa
const
,itcannotbemodified.Thisessentiallyprovidesthesame
viewablebehaviorascall-by-value.Thesignaturewouldbe
string randomItem( const vector<string> & & arr r ); // returns a random m item m in n arr
Thisformofparameterpassingisknownascall-by-reference-to-a-constantinC
++
,but
asthatisoverlyverboseandthe
const
precedesthe
&
,itisalsoknown by thesimpler
terminologyofcall-by-constantreference
.
Theparameter-passing mechanism m for C
++
priorto C
++
11 can thus generally be
decidedbyatwo-parttest:
VB.NET PowerPoint: VB Code to Draw and Create Annotation on PPT
for limitations (other documents are compatible, including PDF, TIFF, MS to install and use Microsoft PowerPoint software and what would you do to add and draw
how to convert pdf into powerpoint slides; convert pdf file to ppt online
VB.NET PowerPoint: Add Image to PowerPoint Document Slide/Page
InsertPage" and "DeletePage" to add, insert or delete any certain PowerPoint slide without affecting the & profession imaging controls, PDF document, tiff
add pdf to powerpoint; convert pdf to powerpoint online no email
1.5 C
++
Details
27
1. Iftheformalparametershouldbeabletochangethevalueoftheactualargument,then
youmustusecall-by-reference.
2. Otherwise,thevalueoftheactualargumentcannotbechangedbytheformalparame-
ter.Ifthetypeisaprimitivetype,usecall-by-value.Otherwise,thetypeisaclasstype
andisgenerallypassedusingcall-by-constant-reference,unlessitisanunusuallysmall
andeasilycopyabletype(e.g.,atypethatstorestwoorfewerprimitivetypes).
Putanotherway,
1. Call-by-value is appropriate for small objects s that t should not be altered by y the
function.
2. Call-by-constant-referenceisappropriateforlargeobjectsthatshouldnotbealtered
bythefunctionandareexpensivetocopy.
3. Call-by-referenceisappropriateforallobjectsthatmaybealteredbythefunction.
BecauseC
++
11addsrvaluereference,thereisafourthwaytopassparameters:call-by-
rvalue-reference.Thecentralconceptisthatsinceanrvaluestoresatemporarythatis
about tobedestroyed,anexpressionsuchas
x=rval
(where
rval
is an rvalue)can be
implementedbyamoveinsteadofacopy;oftenmovinganobject’sstateismucheasier
thancopyingit,asitmayinvolvejustasimplepointerchange.Whatweseehereisthat
x=y
canbeacopyif
y
isanlvalue,butamoveif
y
isanrvalue.Thisgivesaprimaryusecase
ofoverloadingafunctionbasedonwhetheraparameterisanlvalueorrvalue,suchas:
string randomItem( const t vector<string> > & & arr ); ; // / returns random m item in lvalue e arr
string randomItem( vector<string> > && & arr );
// returns random m item in rvalue e arr
vector<string> v v { { "hello", "world" };
cout << randomItem( ( v v ) ) << endl;
// invokes lvalue e method
cout << randomItem( ( { { "hello", , "world" " } } ) ) << endl; // invokes rvalue e method
Itiseasytotestthatwithbothfunctionswritten,thesecondoverloadiscalledonrvalues,
whilethefirstoverloadiscalledonlvalues,asshownabove.Themostcommonuseofthis
idiomisindefiningthebehaviorof
=
andinwritingconstructors,andthisdiscussionis
deferreduntilSection1.5.6.
1.5.4 ReturnPassing
InC
++
,thereareseveraldifferentmechanismsforreturningfromafunction.Themost
straightforwardmechanismtouseisreturn-by-value,asshowninthesesignatures:
double average( double a, , double e b b );
// returns average of f a a and b
LargeType randomItem( ( const t vector<LargeType> > & & arr r );
// potentially inefficient
vector<int> partialSum( ( const t vector<int> & & arr );
// efficient t in n C++11
Thesesignaturesallconveythebasicideathatthefunctionreturnsanobjectofan
appropriatetypethatcanbeusedbythecaller;inallcasestheresultofthefunctioncallis
anrvalue.However,thecallto
randomItem
haspotentialinefficiencies.Thecallto
partialSum
similarlyhaspotentialinefficiencies,thoughinC
++
11thecallislikelytobeveryefficient.
VB.NET PowerPoint: VB Codes to Create Linear and 2D Barcodes on
Here is a market-leading PowerPoint barcode add-on within VB.NET class, which means it as well as 2d barcodes QR Code, Data Matrix, PDF-417, etc.
convert pdf to powerpoint with; add pdf to powerpoint presentation
VB.NET PowerPoint: Extract & Collect PPT Slide(s) Using VB Sample
Add(tmpFilePath1) docPathList.Add(tmpFilePath2) PPTXDocument this VB.NET PowerPoint slide processing tutorial & profession imaging controls, PDF document, image
pdf to ppt converter online for large; copying image from pdf to powerpoint
28
Chapter1 Programming:AGeneralOverview
1
LargeType randomItem1( ( const vector<LargeType> & arr )
2
{
3
return arr[ [ randomInt( 0, , arr.size( ( ) ) - 1 1 ) ) ];
4
}
5
6
const LargeType e & & randomItem2( const vector<LargeType> & & arr r )
7
{
8
return arr[ [ randomInt( 0, , arr.size( ( ) ) - 1 1 ) ) ];
9
}
10
11
vector<LargeType> vec;
12
...
13
LargeType item1 = randomItem1( ( vec c );
// copy
14
LargeType item2 = randomItem2( ( vec c );
// copy
15
const LargeType e & item3 = randomItem2( ( vec c );
// no copy
Figure1.12 Twoversionstoobtainarandomiteminanarray;secondversionavoids
creation ofatemporary
LargeType
object,butonly ifcalleraccessesitwithaconstant
reference
First,considertwoimplementationsof
randomItem
.Thefirstimplementation,shown
inlines1–4ofFigure1.12usesreturn-by-value.Asaresult,the
LargeType
attherandom
arrayindexwillbecopiedaspartofthereturnsequence.Thiscopyisdonebecause,in
general,returnexpressionscouldbervalues(e.g.,return
x+4
)andhencewillnotlogically
existbythetimethefunctioncallreturnsatline13.Butinthiscase,thereturntypeis
anlvaluethatwillexistlongafterthefunctioncallreturns,since
arr
isthesameas
vec
.
Thesecondimplementationshownatlines6–9takesadvantageofthisandusesreturn-
by-constant-referencetoavoidanimmediatecopy.However,thecallermustalsousea
constantreferencetoaccessthereturnvalue,asshownatline15;otherwise,therewill
stillbeacopy.Theconstantreferencesignifiesthatwedonotwanttoallowchangestobe
madebythecallerbyusingthereturnvalue;inthiscaseitisneededsince
arr
itselfisa
non-modifiable
vector
.Analternativeistouse
auto&
atline15todeclare
item3
.
Figure1.13illustratesasimilarsituationinwhichcall-by-valuewasinefficientinclas-
sicC
++
duetothecreationandeventualcleanupofacopy.Historically,C
++
programmers
havegonetogreatextenttorewritetheircodein an unnaturalway,using techniques
involvingpointersoradditionalparametersthatdecreasereadabilityandmaintainability,
eventuallyleadingtoprogrammingerrors.InC
++
11,objectscandefinemovesemantics
that canbeemployedwhen return-by-valueisseen;in effect,theresult
vector
willbe
movedto
sums
,andthe
vector
implementationisoptimizedtoallowthistobedonewith
littlemorethanapointerchange.Thismeansthat
partialSum
asshowninFigure1.13can
beexpectedtoavoidunnecessarycopyingandnotneedanychanges.Thedetailsonhow
movesemanticsareimplementedarediscussedinSection1.5.6;a
vector
implementation
isdiscussedinSection3.4.Noticethatthemovesemanticscanbecalledon
result
atline
9inFigure1.13butnotonthereturnedexpressionatline3inFigure1.12.Thisisacon-
sequenceofthedistinctionbetweenatemporaryandanon-temporary,andthedistinction
betweenanlvaluereferenceandanrvaluereference.
1.5 C
++
Details
29
1
vector<int> partialSum( const t vector<int> > & & arr r )
2
{
3
vector<int> result( ( arr.size( ) );
4
5
result[ 0 0 ] ] = arr[ 0 ];
6
for( int i = 1; i i < < arr.size( ); ++i i )
7
result[ i i ] = = result[ i i - 1 ] ] + + arr[ i ];
8
9
return result;
10
}
11
12
vector<int> vec;
13
...
14
vector<int> sums s = partialSum( ( vec c ); // Copy in old d C
++
; move in C
++
11
Figure1.13 Returningofastack-allocatedrvalueinC
++
11
Inadditiontothereturn-by-valueandreturn-by-constant-referenceidioms,functions
canusereturn-by-reference.Thisidiomisusedinafewplacestoallowthecallerofa
functiontohavemodifiableaccesstotheinternaldatarepresentationofaclass.Return-by-
referenceinthiscontextisdiscussedinSection1.7.2whenweimplementasimplematrix
class.
1.5.5 std::swapandstd::move
Throughoutthissection,wehavediscussed instancesinwhich C
++
11allowsthepro-
grammertoeasilyreplaceexpensivecopieswithmoves.Yetanotherexampleofthisis
theimplementationofa
swap
routine.Swapping
doubles
iseasilyimplementedwiththree
copies,asshowninFigure1.14.However,althoughthesamelogicworkstoswaplarger
types,itcomeswithasignificantcost:Nowthecopiesareveryexpensive!However,itis
easytoseethatthereisnoneedtocopy;whatweactuallywantistodomovesinstead
ofcopies.InC
++
11,iftheright-handsideoftheassignmentoperator(orconstructor)is
anrvalue,theniftheobjectsupportsmoving,wecanautomaticallyavoidcopies.Inother
words,if
vector<string>
supportsefficientmoving,andifatline10
x
wereanrvalue,then
x
couldbemovedinto
tmp
;similarly,ifywasanrvalueatline11,thenitcouldbemoved
into
y
.
vector
doesindeedsupportmoving;however,
x, y
,and
tmp
arealllvaluesatlines
10,11,12(remember,ifanobjecthasaname,itisanlvalue).Figure1.15showshow
thisproblemissolved;animplementationof
swap
atlines1–6showsthatwecanusea
casttotreattheright-handsideoflines10–12asrvalues.Thesyntaxofastaticcastis
daunting;fortunately,function
std::move
existsthatconvertsanylvalue(orrvalue)intoan
rvalue.Notethatthenameismisleading;
std::move
doesn’tmoveanything;rather,itmakes
avaluesubjecttobemoved.Useof
std::move
isalsoshowninarevisedimplementationof
swap
atlines8–13ofFigure1.15.Theswapfunction
std::swap
isalsopartoftheStandard
Libraryandwillworkforanytype.
30
Chapter1 Programming:AGeneralOverview
1
void swap( ( double & x, double & & y y )
2
{
3
double tmp = x;
4
x = y;
5
y = tmp;
6
}
7
8
void swap( ( vector<string> & x, vector<string> > & & y )
9
{
10
vector<string> tmp = x;
11
x = y;
12
y = tmp;
13
}
Figure1.14 Swappingbythreecopies
1
void swap( ( vector<string> & x, vector<string> > & & y )
2
{
3
vector<string> tmp = static_cast<vector<string> &&>( ( x x );
4
x = static_cast<vector<string> > &&>( y y );
5
y = static_cast<vector<string> > &&>( tmp p );
6
}
7
8
void swap( ( vector<string> & x, vector<string> > & & y )
9
{
10
vector<string> tmp = std::move( x );
11
x = std::move( y y );
12
y = std::move( tmp );
13
}
Figure1.15 Swappingbythreemoves;firstwithatypecast,secondusingstd::move
1.5.6 TheBig-Five:Destructor,CopyConstructor,Move
Constructor,CopyAssignmentoperator=,Move
Assignmentoperator=
InC
++
11,classescomewithfivespecialfunctionsthatarealreadywrittenforyou.These
arethedestructor,copyconstructor,move constructor,copyassignmentoperator,
andmoveassignmentoperator.Collectivelythesearethebig-five.Inmanycases,you
canacceptthedefaultbehaviorprovidedbythecompilerforthebig-five.Sometimesyou
cannot.
Destructor
Thedestructoriscalledwheneveranobjectgoesoutofscopeorissubjectedtoa
delete
.
Typically,theonlyresponsibilityofthedestructoristofreeupanyresourcesthatwere
1.5 C
++
Details
31
acquiredduringtheuseoftheobject.Thisincludescalling
delete
foranycorrespond-
ing
new
s,closinganyfilesthatwereopened,andsoon.Thedefaultsimplyappliesthe
destructoroneachdatamember.
CopyConstructorandMoveConstructor
Therearetwospecialconstructorsthatarerequiredtoconstructanewobject,initialized
tothesamestateasanotherobjectofthesametype.Thesearethecopyconstructorifthe
existingobjectisanlvalue,andthemoveconstructoriftheexistingobjectisanrvalue
(i.e.,atemporarythatisabouttobedestroyedanyway).Foranyobject,suchasan
IntCell
object,acopyconstructorormoveconstructoriscalledinthefollowinginstances:
adeclarationwithinitialization,suchas
IntCell B =C;
// Copy constructif C is lvalue;Move construct if C isrvalue
IntCell B {C }; // Copy constructif C is lvalue;Move construct if C isrvalue
butnot
B = = C;
// Assignment operator, discussed d later
anobjectpassedusingcall-by-value(insteadofby
&
or
const &
),which,asmentioned
earlier,shouldrarelybedoneanyway.
anobjectreturnedbyvalue(insteadofby
&
or
const &
).Again,acopyconstructoris
invokediftheobjectbeingreturnedisanlvalue,andamoveconstructorisinvokedif
theobjectbeingreturnedisanrvalue.
Bydefault,thecopyconstructorisimplementedbyapplyingcopyconstructorstoeach
datamemberinturn.Fordatamembersthatareprimitivetypes(forinstance,
int
,
double
,
orpointers),simpleassignmentisdone.Thiswouldbethecaseforthe
storedValue
data
memberinour
IntCell
class.Fordatamembersthatarethemselvesclassobjects,thecopy
constructorormoveconstructor,asappropriate,foreachdatamember’sclassisappliedto
thatdatamember.
CopyAssignmentandMoveAssignment(operator=)
Theassignmentoperatoriscalledwhen
=
isappliedtotwoobjectsthathavebothbeen
previouslyconstructed.
lhs=rhs
isintendedtocopythestateof
rhs
into
lhs
.If
rhs
isan
lvalue,thisisdonebyusingthecopyassignmentoperator;if
rhs
isanrvalue(i.e.,atem-
porarythatisabouttobedestroyedanyway),thisisdonebyusingthemoveassignment
operator.Bydefault,thecopyassignmentoperatorisimplementedbyapplyingthecopy
assignmentoperatortoeachdatamemberinturn.
Defaults
Ifweexaminethe
IntCell
class,weseethatthedefaultsareperfectlyacceptable,sowe
donothavetodoanything.Thisisoftenthecase.Ifaclassconsistsofdatamembers
thatareexclusivelyprimitivetypesandobjectsforwhichthedefaultsmakesense,the
classdefaultswillusuallymakesense.Thusaclasswhosedatamembersare
int
,
double
,
vector<int>
,
string
,andeven
vector<string>
canacceptthedefaults.
Documents you may be interested
Documents you may be interested