C++ Overview Douglas C. Schmidt An Overview of C++
Transcript of C++ Overview Douglas C. Schmidt An Overview of C++
An
Overv
iew
ofC+
+
Dougla
sC.Sch
mid
t
Professor
Dep
artmen
tof
EECS
d.sch
mid
t@van
derb
ilt.edu
Van
derb
iltU
niversity
ww
w.d
re.vanderb
ilt.edu/∼
schm
idt/
(615)343-8197
ww
w.d
re.vanderb
ilt.edu/∼
schm
idt/P
DF/C
++
-overview.p
df
January
18,2012
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
C+
+O
vervie
w
•C+
+was
design
edat
AT
&T
Bell
Lab
sby
Bjarn
eStrou
strup
inth
eearly
80’s–
nearly
30years
ago!
–T
he
original
cfront
translated
C+
+in
toC
forportab
ility∗
How
ever,th
iswas
diffi
cult
todeb
ug
and
poten
tiallyin
efficien
t–
Man
ynative
host
mach
ine
compilers
now
exist∗
e.g.,C+
+B
uild
er,clan
g,Com
eauC/C
++
,G
CC,In
telC+
+Com
piler,
Microsoft
Visu
alC+
+,Sun
Stu
dio,
etc.
•C+
+is
am
ostlyupw
ardly
compatib
leexten
sionof
Cth
atprovid
es:
1.Stron
gertyp
echeckin
g2.
Support
fordata
abstraction
3.Support
forob
ject-oriented
programm
ing
4.Support
forgen
ericprogram
min
g
Van
derb
iltU
niversity
1
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
C+
+D
esig
nGoals
•A
sw
ithC,ru
n-tim
eeffi
ciency
isim
portan
t
–U
nlike
other
langu
ages(e.g.,
Ada,
Java,C#
,etc.)
complicated
run-tim
elibraries
and
virtual
mach
ines
have
not
tradition
allybeen
required
forC+
+∗
Note,
that
there
isno
langu
age-specifi
csu
pport
forcon
curren
cy,persisten
ce,or
distrib
ution
inC+
+
•Com
patib
ilityw
ithC
libraries&
tradition
aldevelop
men
tto
olsis
emphasized
,e.g.,
–O
bject
code
reuse
∗T
he
storagelayou
tof
structu
resis
compatib
lew
ithC
∗e.g.,
support
forX
-win
dow
s,stan
dard
AN
SIC
library,&
UN
IX/W
IN32
systemcalls
viaextern
blo
ck–
C+
+works
with
themake
recompilation
utility
Van
derb
iltU
niversity
2
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
C+
+D
esig
nGoals
(cont’d
)
•“A
sclose
toC
aspossib
le,but
no
closer”
–i.e.,
C+
+is
not
aprop
ersu
perset
ofC→
backw
ards
compatib
ilityis
not
entirely
main
tained
∗Typ
icallynot
aprob
lemin
practice...
•N
ote,certain
C+
+design
goalscon
flict
with
modern
techniq
ues
for:
1.Com
piler
optim
ization–
e.g.,poin
tersto
arbitrary
mem
orylo
cations
complicate
registerallo
cation&
garbage
collection2.
Softw
areen
gineerin
g–
e.g.,sep
aratecom
pilation
complicates
inlin
ing
due
todiffi
culty
ofin
terproced
ural
analysis
–D
ynam
icm
emory
man
agemen
tis
error-prone
Van
derb
iltU
niversity
3
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Majo
rC+
+Enhance
ments
1.C+
+su
pports
data
abstraction
&en
capsu
lation
•e.g.,
the
classm
echan
ism&
nam
esp
aces
2.C+
+su
pports
object-orien
tedprogram
min
gfeatu
res
•e.g.,
abstract
classes,in
heritan
ce,&
virtual
meth
ods
3.C+
+su
pports
generic
programm
ing
•e.g.,
param
eterizedtyp
es
4.C+
+su
pports
sophisticated
errorhan
dlin
g
•e.g.,
exception
han
dlin
g
5.C+
+su
pports
iden
tifying
anob
ject’styp
eat
runtim
e
•e.g.,
Run-T
ime
Typ
eId
entifi
cation(R
TT
I)
Van
derb
iltU
niversity
4
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Importa
nt
Min
orC+
+Enhance
ments
•C+
+en
forcestyp
ech
ecking
viafu
nction
prototypes
•Provid
estyp
e-safelin
kage
•Provid
esin
line
function
expan
sion
•D
eclarecon
stants
that
canbe
used
todefi
ne
staticarray
bou
nds
with
theconst
type
qualifi
er
•B
uilt-in
dyn
amic
mem
orym
anagem
ent
vianew
&delete
operators
•N
amesp
acecon
trol
Van
derb
iltU
niversity
5
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Use
fulM
inorC+
+Enhance
ments
•T
he
nam
eof
astruct,class,enum,or
union
isa
type
nam
e
•Referen
cesallow
“call-by-reference”
param
eterm
odes
•N
ewtyp
e-secure
extensib
leiostream
sI/O
mech
anism
•“F
unction
call”-stylecast
notation
•Several
diff
erent
comm
entin
gstyles
•N
ewmutable
type
qualifi
er
•N
ewbool
boolean
type
Van
derb
iltU
niversity
6
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Questio
nable
C+
+Featu
res
•D
efault
values
forfu
nction
param
eters
•O
perator
&fu
nction
overloadin
g
•Variab
ledeclaration
sm
ayoccu
ran
ywhere
statemen
tsm
ayap
pear
with
ina
blo
ck
•A
llows
user-d
efined
conversion
operators
•Static
data
initializers
may
be
arbitrary
expressions
Van
derb
iltU
niversity
7
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Language
Featu
res
Not
Part
ofC+
+
1.Con
curren
cy
•“C
oncu
rrent
C”
byG
ehan
i•
Actor+
+m
odel
byLaven
der
&K
afura
2.Persisten
ce
•O
bject
Store,
Versan
t,O
bjectivity
•Exo
dus
system&
Eprogram
min
glan
guage
3.G
arbage
Collection
•U
SEN
IXC+
+1994
pap
erby
Ellis
&D
etlefs•
GN
Ug+
+
4.D
istribution
•CO
RB
A,D
DS,CO
M+
,SO
AP,etc.
Van
derb
iltU
niversity
8
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Stra
tegie
sfo
rLearn
ing
C+
+
•Focu
son
concep
ts&
programm
ing
techniq
ues
–D
on’t
getlost
inlan
guage
features
•Learn
C+
+to
becom
ea
better
programm
er
–M
oreeff
ectiveat
design
ing
&im
plem
entin
g–
Design
Pattern
s
•C+
+su
pports
man
ydiff
erent
programm
ing
styles
•Learn
C+
+grad
ually
–D
on’t
have
tokn
owevery
detail
ofC+
+to
write
ago
od
C+
+program
Van
derb
iltU
niversity
9
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Sta
ckExa
mple
•T
he
followin
gslid
esexam
ine
severalalterative
meth
ods
ofim
plem
entin
ga
Stack
–B
eginw
ithC
&evolve
up
tovariou
sC+
+im
plem
entation
s
•First,
consid
erth
e“b
are-bon
es”im
plem
entation
:
typedef
int
T;
#define
MAX_STACK
100
/*const
int
MAX_STACK
=100;
*/
Tstack[MAX_STACK];
int
top
=0;
Titem
=10;
stack[top++]
=item;
//
push
...
item
=stack[--top];
//
pop
•O
bviou
slynot
veryab
stract...
Van
derb
iltU
niversity
10
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Data
Hid
ing
Imple
menta
tion
inC
•D
efine
the
interface
toa
Stack
ofin
tegersin
Cin
Stack.h
:
/*
Type
of
Stack
element.
*/
typedef
int
T;
/*
Stack
interface.
*/
int
create
(int
size);
int
destroy
(void);
void
push
(T
new_item);
void
pop
(T
*old_top);
void
top
(T
*cur_top);
int
is_empty
(void);
int
is_full
(void);
Van
derb
iltU
niversity
11
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Data
Hid
ing
Imple
menta
tion
inC
(cont’d
)•
/*File
stack.c*/
#include
"stack.h"
static
int
top_,
size_;
/*
Hidden
within
this
file.
*/
static
T*stack_;
int
create
(int
size)
{
top_
=0;
size_
=size;
stack_
=malloc
(size
*sizeof
(T));
return
stack_
==
0?
-1
:0;
}void
destroy
(void)
{free
((void
*)
stack_);
}
void
push
(T
item)
{stack_[top_++]
=item;}
void
pop
(T
*item)
{*item
=stack_[--top_];
}
void
top
(T
*item)
{*item
=stack_[top_
-1];
}
int
is_empty
(void)
{return
top_
==
0;
}
int
is_full
(void)
{return
top_
==
size_;
}
Van
derb
iltU
niversity
12
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Data
Hid
ing
Imple
menta
tion
inC
(cont’d
)•
Use
case
#include
"stack.h"
void
foo
(void)
{
Ti;
push
(10);
/*
Oops,
forgot
to
call
create!
*/
push
(20);
pop
(&i);
destroy
();
}
•M
ainprob
lems:
1.T
he
programm
erm
ust
callcreate()
first
&destroy()
last!2.
There
ison
lyon
estack
&on
lyon
etyp
eof
stack3.
Nam
esp
acepollu
tion...
4.N
on-reen
trant
Van
derb
iltU
niversity
13
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Data
Abstra
ction
Imple
menta
tion
inC
•A
nA
DT
Stack
interface
inC:
typedef
int
T;
typedef
struct
{size_t
top_,
size_;
T*stack_;
}Stack;
int
Stack_create
(Stack
*s,
size_t
size);
void
Stack_destroy
(Stack
*s);
void
Stack_push
(Stack
*s,
Titem);
void
Stack_pop
(Stack
*,T
*item);
/*
Must
call
before
pop’ing
*/
int
Stack_is_empty
(Stack
*);
/*
Must
call
before
push’ing
*/
int
Stack_is_full
(Stack
*);
/*
...
*/
Van
derb
iltU
niversity
14
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Data
Abstra
ction
Imple
menta
tion
inC
(cont’d
)•
An
AD
TStack
implem
entation
inC:
#include
"stack.h"
int
Stack_create
(Stack
*s,
size_t
size)
{
s->top_
=0;
s->size_
=size;
s->stack_
=malloc
(size
*sizeof
(T));
return
s->stack_
==
0?
-1
:0;
}void
Stack_destroy
(Stack
*s)
{
free
((void
*)
s->stack_);
s->top_
=0;
s->size_
=0;
s->stack_
=0;
}void
Stack_push
(Stack
*s,
Titem)
{s->stack_[s->top_++]
=item;
}
void
Stack_pop
(Stack
*s,
T*item)
{*item
=s->stack_[--s->top_];
}
int
Stack_is_empty
(Stack
*s)
{return
s->top_
==
0;
}
Van
derb
iltU
niversity
15
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Data
Abstra
ction
Imple
menta
tion
inC
(cont’d
)•
Use
case
void
foo
(void)
{
Stack
s1,
s2,
s3;
/*
Multiple
stacks!
*/
Titem;
Stack_pop
(&s2,
&item);
/*
Pop’d
empty
stack
*/
/*
Forgot
to
call
Stack_create!
*/
Stack_push
(&s3,
10);
s2
=s3;
/*
Disaster
due
to
aliasing!!!
*/
/*
Destroy
uninitialized
stacks!
*/
Stack_destroy
(&s1);
Stack_destroy
(&s2);
}
Van
derb
iltU
niversity
16
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Main
pro
ble
ms
with
Data
Abstra
ction
inC
1.N
ogu
aranteed
initialization
,term
ination
,or
assignm
ent
2.Still
only
one
type
ofstack
supported
3.Too
much
overhead
due
tofu
nction
calls
4.N
ogen
eralizederror
han
dlin
g...
5.T
he
Ccom
piler
does
not
enforce
inform
ationhid
ing
e.g.,
s1.top_
=s2.stack_[0];
/*
Violate
abstraction
*/
s2.size_
=s3.top_;
/*
Violate
abstraction
*/
Van
derb
iltU
niversity
17
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Data
Abstra
ction
Imple
menta
tion
inC+
+•
We
canget
encap
sulation
and
more
than
one
stack:
typedef
int
T;
class
Stack
{
public:
Stack
(size_t
size);
Stack
(const
Stack
&s);
void
operator=
(const
Stack
&);
~Stack
(void);
void
push
(const
T&item);
void
pop
(T
&item);
bool
is_empty
(void)
const;
bool
is_full
(void)
const;
private:
size_t
top_,
size_;
T*stack_;
};
Van
derb
iltU
niversity
18
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Data
Abstra
ction
Imple
menta
tion
inC+
+(co
nt’d
)•
Man
agerop
erations
Stack::Stack
(size_t
s):
top_
(0),
size_
(s),
stack_
(new
T[s])
{}
Stack::Stack
(const
Stack
&s)
:top_
(s.top_),
size_
(s.size_),
stack_
(new
T[s.size_])
{for
(size_t
i=
0;
i<
s.size_;
++i)
stack_[i]
=s.stack_[i];
}
void
Stack::operator=
(const
Stack
&s)
{
if
(this
==
&s)
return;
T*temp_stack
=new
T[s.size_];
delete
[]
stack_;
stack_
=0;
for
(size_t
i=
0;
i<
s.size_;
++i)
temp_stack[i]
=s.stack_[i];
stack_
=temp_stack;
top_
=s.top_;
size_
=s.size_;
}Stack::~Stack
(void)
{delete
[]stack_;
}
Van
derb
iltU
niversity
19
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Data
Abstra
ction
Imple
menta
tion
inC+
+(co
nt’d
)
•A
ccessor&
worker
operation
s
bool
Stack::is_empty
(void)
const
{return
top_
==
0;
}
bool
Stack::is_full
(void)
const
{return
top_
==
size_;
}
void
Stack::push
(const
T&item)
{stack_[top_++]
=item;
}
void
Stack::pop
(T
&item)
{item
=stack_[--top_];
}
Van
derb
iltU
niversity
20
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Data
Abstra
ction
Imple
menta
tion
inC+
+(co
nt’d
)•
Use
case
#include
"Stack.h"
void
foo
(void)
{
Stack
s1
(1),
s2
(100);
Titem;
if
(!s1.is_full
())
s1.push
(473);
if
(!s2.is_full
())
s2.push
(2112);
if
(!s2.is_empty
())
s2.pop
(item);
//
Access
violation
caught
at
compile-time!
s2.top_
=10;
//
Termination
is
handled
automatically.
}
Van
derb
iltU
niversity
21
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Benefits
ofC+
+D
ata
Abstra
ction
Imple
menatio
n
1.D
atahid
ing
&data
abstraction
,e.g.,
Stack
s1
(200);
s1.top_
=10
//
Error
flagged
by
compiler!
2.T
he
ability
todeclare
multip
lestack
objects
Stack
s1
(10),
s2
(20),
s3
(30);
3.A
utom
aticin
itialization&
termin
ation
{
Stack
s1
(1000);
//
constructor
called
automatically.
//
...
//
Destructor
called
automatically
}
Van
derb
iltU
niversity
22
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Draw
back
sw
ithC+
+D
ata
Abstra
ction
Imple
menta
tion
1.Error
han
dlin
gis
obtru
sive
•U
seexcep
tionhan
dlin
gto
solveth
is(b
ut
be
careful)!
2.T
he
example
islim
itedto
asin
gletyp
eof
stackelem
ent(in
tin
this
case)
•W
ecan
use
C+
+“p
arameterized
types”
torem
oveth
islim
itation
3.Function
calloverh
ead
•W
ecan
use
C+
+in
line
function
sto
remove
this
overhead
Van
derb
iltU
niversity
23
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Exce
ptio
nH
andlin
gIm
ple
menta
tion
inC+
+(co
nt’d
)•
C+
+excep
tions
separate
errorhan
dlin
gfrom
norm
alpro
cessing
typedef
....
T;
//
Where
"...."
is
aplaceholder
for
any
C++
type.
class
Stack
{
public:
class
Underflow
{/*
...
*/
};
//
WARNING:
be
cautious
when
using
class
Overflow
{/*
...
*/
};
//
exception
specifiers...
Stack
(size_t
size);
Stack
(const
Stack
&rhs);
void
operator=
(const
Stack
&rhs);
~Stack
(void);
void
push
(const
T&item)
throw
(Overflow);
void
pop
(T
&item)
throw
(Underflow);
//
...
private:
size_t
top_,
size_;
T*stack_;
};
Van
derb
iltU
niversity
24
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Exce
ptio
nH
andlin
gIm
ple
menta
tion
inC+
+(co
nt’d
)
•Stack.cp
p
Stack::Stack
(size_t
s):
top_
(s),
size_
(s),
stack_
(new
T[s])
{}
Stack::~Stack
()
{delete
[]
stack_;
}
void
Stack::push
(const
T&item)
throw
(Stack::Overflow)
{
if
(is_full
())
throw
Stack::Overflow
();
stack_[top_++]
=item;
}void
Stack::pop
(T
&item)
throw
(Stack::Underflow)
{
if
(is_empty
())
throw
Stack::Underflow
();
item
=stack_[--top_];
}
Van
derb
iltU
niversity
25
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Exce
ptio
nH
andlin
gIm
ple
menta
tion
inC+
+(co
nt’d
)•
Stack.cp
p
Stack::Stack
(const
Stack
&s):
:top_
(s.top_),
size_
(s.size_),
stack_
(0)
{
scoped_array<T>
temp_stack
(new
T[s.size_]);
for
(size_t
i=0;
i<s.size_;
++i)
temp_stack[i]
=s.stack_[i];
temp_stack.swap
(stack_);
}void
Stack::operator=
(const
Stack
&s)
{
if
(this
==
&s)
return;
//
Check
for
self-assignment
scoped_array<T>
temp_stack
(new
T[s.size_]);
for
(size_t
i=0;
i<s.size_;
++i)
temp_stack[i]
=s.stack_[i];
top_
=s.top_;
size_
=s.size_;
temp_stack.swap
(stack_);
}
Van
derb
iltU
niversity
26
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Exce
ptio
nH
andlin
gIm
ple
menta
tion
inC+
+(co
nt’d
)•scopedarray
extendsautoptr
todestroy
built-in
arrays
template
<typename
T>
class
scoped_array
{
public:
explicit
scoped_array
(T
*p
=0)
:ptr_
(p)
{}
~scoped_array
()
{delete
[]
ptr_;
}
T&operator[](std::ptrdiff_t
i)
const
{return
ptr_[i];
}
T*get()
const
{return
ptr_;
}
void
swap
(T
*&b)
{T*tmp
=b;
b=
ptr_;
ptr_
=tmp;
}
void
swap
(scoped_array<T>
&b)
{T*tmp
=b.ptr_;
b.ptr_
=this->ptr_;
this->ptr_
=tmp;
}
private:
T*ptr_;
scoped_array
(const
scoped_array<T>
&);
scoped_array
&operator=(const
scoped_array<T>
&);
};
Van
derb
iltU
niversity
27
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Exce
ptio
nH
andlin
gIm
ple
menta
tion
inC+
+(co
nt’d
)•
There’s
abetter
way
toim
plem
entoperator=():
void
Stack::operator=
(const
Stack
&s)
{
if
(this
==
&s)
return;
//
Check
for
self-assignment
Stack
t(s);
std::swap
(t.top_,
top_);
std::swap
(t.size_,
size_);
std::swap
(t.stack_,
stack_);
}//
Old
way:
void
Stack::operator=
(const
Stack
&s)
{
if
(this
==
&s)
return;
//
Check
for
self-assignment
scoped_array<T>
temp_stack
(new
T[s.size_]);
for
(size_t
i=0;
i<s.size_;
++i)
temp_stack[i]
=s.stack_[i];
top_
=s.top_;
size_
=s.size_;
temp_stack.swap
(stack_);
}
Van
derb
iltU
niversity
28
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Exce
ptio
nH
andlin
gIm
ple
menta
tion
inC+
+(co
nt’d
)
•A
nd
yetan
evenbetter
way
toim
plem
ent
exception
-safeStack:
class
Stack
{//
...
private:
//
...
scoped_array<T>
stack_;
void
swap
(Stack
&);
};
//
...
Stack::Stack
(const
Stack
&s)
:top_
(s.top_),
size_
(s.size_),
stack_
(new
T[s.size_])
{
for
(size_t
i=
0;
i<
s.size_;
++i)
stack_[i]
=s.stack_[i];
}Stack::~Stack
()
{/*
no-op!
*/
}
Van
derb
iltU
niversity
29
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Exce
ptio
nH
andlin
gIm
ple
menta
tion
inC+
+(co
nt’d
)
•A
nd
yetan
evenbetter
way
toim
plem
entoperator=():
void
Stack::operator=
(const
Stack
&s)
{
if
(this
==
&s)
return;
//
Check
for
self-assignment
Stack
temp_stack
(s);
swap
(temp_stack);
}void
Stack::swap
(Stack
&t)
{
std::swap
(t.top_,
top_);
std::swap
(t.size_,
size_);
t.stack_.swap
(stack_);
}
•T
his
solution
iseasy
togen
eralize!
Van
derb
iltU
niversity
30
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Exce
ptio
nH
andlin
gIm
ple
menta
tion
inC+
+(co
nt’d
)•
Use
case
#include
"Stack.h"
void
foo
(void)
{
Stack
s1
(1),
s2
(100);
try
{
Titem;
s1.push
(473);
s1.push
(42);
//
Exception,
push’d
full
stack!
s2.pop
(item);
//
Exception,
pop’d
empty
stack!
s2.top_
=10;
//
Access
violation
caught!
}catch
(Stack::Underflow)
{/*
Handle
underflow...
*/
}
catch
(Stack::Overflow)
{/*
Handle
overflow...
*/
}
catch
(...)
{/*
Catch
anything
else...
*/
throw;
}
}//
Termination
is
handled
automatically.
}
Van
derb
iltU
niversity
31
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Tem
pla
teIm
ple
menta
tion
inC+
+•
Aparam
eterizedtyp
eStack
classin
terfaceusin
gC+
+
template
<typename
T>
class
Stack
{
public:
Stack
(size_t
size);
Stack
(const
Stack<T>
&rhs);
void
operator=
(const
Stack<T>
&rhs);
~Stack
(void)
void
push
(const
T&item);
void
pop
(T
&item);
bool
is_empty
(void)
const;
bool
is_full
(void)
const;
private:
size_t
top_,
size_;
scoped_array<T>
stack_;
void
swap
(scoped_array<T>
&t);
};
Van
derb
iltU
niversity
32
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Tem
pla
teIm
ple
menta
tion
inC+
+(co
nt’d
)
•A
param
eterizedtyp
eStack
classim
plem
entation
usin
gC+
+
template
<typename
T>
inline
Stack<T>::Stack
(size_t
size)
:top_
(0),
size_
(size),
stack_
(new
T[size])
{}
template
<typename
T>
inline
Stack<T>::~Stack
(void)
{/*
no-op!
*/
}
template
<typename
T>
inline
void
Stack<T>::push
(const
T&item)
{stack_[top_++]
=item;
}
template
<typename
T>
inline
void
Stack<T>::pop
(T
&item)
{item
=stack_[--top_];
}
//
...
Van
derb
iltU
niversity
33
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Tem
pla
teIm
ple
menta
tion
inC+
+(co
nt’d
)•
Note
min
orch
anges
toaccom
modate
param
eterizedtyp
es
#include
"Stack.h"
void
foo
(void)
{
Stack<int>
s1
(1000);
Stack<float>
s2;
Stack<
Stack
<Activation_Record>
*>
s3;
s1.push
(-291);
s2.top_
=3.1416;
//
Access
violation
caught!
s3.push
(new
Stack<Activation_Record>);
Stack
<Activation_Record>
*sar;
s3.pop
(sar);
delete
sar;
//
Termination
of
s1,
s2,
&s3
handled
automatically
}
Van
derb
iltU
niversity
34
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Tem
pla
teIm
ple
menta
tion
inC+
+(co
nt’d
)•
Anoth
erparam
eterizedtyp
eStack
class
template
<typename
T,
size_t
SIZE>
class
Stack
{
public:
Stack
(void);
~Stack
(void)
void
push
(const
T&item);
void
pop
(T
&item);
private:
size_t
top_,
size_;
Tstack_[SIZE];
};
•N
oneed
fordyn
amic
mem
ory,th
ough
SIZ
Em
ust
be
const,
e.g.,
Stack<int,
200>
s1;
Van
derb
iltU
niversity
35
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Obje
ct-Orie
nte
dIm
ple
menta
tion
inC+
+
•Prob
lems
with
previous
examples:
–Chan
gesto
the
implem
entation
will
require
recompilation
&relin
king
ofclien
ts–
Exten
sions
will
require
accessto
the
source
code
•Solu
tions
–Com
bin
ein
heritan
cew
ithdyn
amic
bin
din
gto
completely
decou
ple
interface
fromim
plem
entation
&bin
din
gtim
e–
This
requires
the
use
ofC+
+ab
stractbase
classes
Van
derb
iltU
niversity
36
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Obje
ct-Orie
nte
dIm
ple
menta
tion
inC+
+(co
nt’d
)
•D
efinin
gan
abstract
base
classin
C+
+
template
<typename
T>
class
Stack
{
public:
virtual
~Stack
(void)
=0;
//
Need
implementation!
virtual
void
push
(const
T&item)
=0;
virtual
void
pop
(T
&item)
=0;
virtual
bool
is_empty
(void)
const
=0;
virtual
bool
is_full
(void)
const
=0;
void
top
(T
&item)
{/*
Template
Method
*/
pop
(item);
push
(item);
}
};
•B
yusin
g“p
ure
virtual
meth
ods,”
we
cangu
arantee
that
the
compiler
won
’tallow
instan
tiation!
Van
derb
iltU
niversity
37
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Obje
ct-Orie
nte
dIm
ple
menta
tion
inC+
+(co
nt’d
)•
Inherit
tocreate
asp
ecializedstack
implem
ented
viaan
ST
Lvector:
#include
"Stack.h"
#include
<vector>
template
<typename
T>
class
V_Stack
:public
Stack<T>
{
public:
enum
{DEFAULT_SIZE
=100
};
V_Stack
(size_t
size
=DEFAULT_SIZE);
V_Stack
(const
V_Stack
&rhs);
virtual
void
push
(const
T&item);
virtual
void
pop
(T
&item);
virtual
bool
is_empty
(void)
const;
virtual
bool
is_full
(void)
const;
private:
size_t
top_;
std::vector<T>
stack_;
};
Van
derb
iltU
niversity
38
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Obje
ct-Orie
nte
dIm
ple
menta
tion
inC+
+(co
nt’d
)
•class
VStack
implem
entation
template
<typename
T>
V_Stack<T>::V_Stack
(size_t
size):
top_
(0),
stack_
(size)
{}
template
<typename
T>
V_Stack<T>::V_Stack
(const
V_Stack
&rhs):
top_
(rhs.top_),
stack_
(rhs.stack_)
{}
template
<typename
T>
void
V_Stack<T>::push
(const
T&item)
{stack_[top_++]
=item;
}
template
<typename
T>
void
V_Stack<T>::pop
(T
&item)
{item
=stack_[--top_];
}
template
<typename
T>
int
V_Stack<T>::is_full
(void)
const
{return
top_
>=
stack_.size
();
}
Van
derb
iltU
niversity
39
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Obje
ct-Orie
nte
dIm
ple
menta
tion
inC+
+(co
nt’d
)•
Inheritan
cecan
alsocreate
anlin
kedlist
stack:
template
<typename
T>
class
Node;
//
forward
declaration.
template
<typename
T>
class
L_Stack
:public
Stack<T>
{
public:
enum
{DEFAULT_SIZE
=100
};
L_Stack
(size_t
hint
=DEFAULT_SIZE);
~L_Stack
(void);
virtual
void
push
(const
T&new_item);
virtual
void
pop
(T
&top_item);
virtual
bool
is_empty
(void)
const
{return
head_
==
0;
}
virtual
bool
is_full
(void)
const
{return
0;
}
private:
//
Head
of
linked
list
of
Node<T>’s.
Node<T>
*head_;
};
Van
derb
iltU
niversity
40
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Obje
ct-Orie
nte
dIm
ple
menta
tion
inC+
+(co
nt’d
)
•class
Node
implem
entation
template
<typename
T>
class
Node
{
friend
template
<typename
T>
class
L_Stack;
public:
Node
(T
i,
Node<T>
*n
=0):
item_
(i),
next_
(n)
{}
private:
Titem_;
Node<T>
*next_;
};
•N
oteth
atth
euse
ofth
e“C
hesh
irecat”
idiom
allows
the
libraryw
riterto
completely
hid
eth
erepresen
tationof
classVStack...
Van
derb
iltU
niversity
41
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Obje
ct-Orie
nte
dIm
ple
menta
tion
inC+
+(co
nt’d
)
•class
LStack
implem
entation
:
template
<typename
T>
L_Stack<T>::L_Stack
(size_t):
head_
(0)
{}
template
<typename
T>
void
L_Stack<T>::push
(const
T&item)
{
Node<T>
*t
=new
Node<T>
(item,
head_);
head_
=t;
}template
<typename
T>
void
L_Stack<T>::pop
(T
&top_item)
{
top_item
=head_->item_;
Node<T>
*t
=head_;
head_
=head_->next_;
delete
t;
}template
<typename
T>
L_Stack<T>::~L_Stack
(void)
{for
(T
t;
head_
!=
0;
pop
(t))
continue;
}
Van
derb
iltU
niversity
42
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Obje
ct-Orie
nte
dIm
ple
menta
tion
inC+
+(co
nt’d
)
•U
sing
our
abstract
base
class,it
ispossib
leto
write
code
that
does
not
dep
end
onth
estack
implem
entation
,e.g.,
Stack<int>
*make_stack
(bool
use_V_Stack)
{return
use_V_Stack
?new
V_Stack<int>
:new
L_Stack<int>;
}
void
print_top
(Stack<int>
*stack)
{
std::cout
<<
"top
="<<
stack->top
()
<<std::endl;
}int
main
(int
argc,
char
**)
{
std::auto_ptr
<Stack<int>>
sp
(make_stack
(argc
>1));
sp->push
(10);
print_top
(sp.get
());
}
Van
derb
iltU
niversity
43
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Obje
ct-Orie
nte
dIm
ple
menta
tion
inC+
+(co
nt’d
)
•M
oreover,we
canm
akech
anges
atru
n-tim
ew
ithou
tm
odifyin
g,recom
pilin
g,or
relinkin
gexistin
gco
de
viadyn
amic
linkin
g:
char
stack_symbol[MAXNAMLEN];
char
stack_file[MAXNAMLEN];
cin
>>
stack_file
>>
stack_factory;
void
*handle
=ACE_OS::dlopen
(stack_file);
Stack<int>
*(*factory)(bool)
=ACE_OS::dlsym
(handle,
stack_factory);
std::auto_ptr
<Stack<int>>
sp
((*factory)
(argc
>1));
sp->push
(10);
print_top
(sp.get
());
•N
ote,no
need
tostop
,m
odify,
&restart
anexecu
ting
application
!
–N
aturally,
this
requires
carefulcon
figu
rationm
anagem
ent...
Van
derb
iltU
niversity
44
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
The
Road
Ahead:
C+
+11
The
modifi
cations
forC+
+in
volveboth
the
corelan
guage
and
the
standard
library:
•Prefer
intro
duction
ofnew
features
throu
ghth
estan
dard
library,rath
erth
anexten
din
gth
ecore
langu
age
•Im
proveC+
+to
facilitatesystem
san
dlibrary
design
,rath
erth
anto
intro
duce
new
features
only
usefu
lto
specifi
cap
plication
s;
•In
creasetyp
esafety
byprovid
ing
saferaltern
ativesto
curren
t,unsafe
techniq
ues;
•In
creaseperform
ance
and
the
ability
towork
directly
with
hard
ware;
•Im
plem
ent
“zero-overhead
”prin
ciple
(addition
alsu
pport
required
bysom
eutilities
must
be
used
only
ifth
eutility
isused
)
•M
akeC+
+easier
toteach
and
tolearn
with
out
removin
gan
yutility
need
edby
expert
programm
ers.
Van
derb
iltU
niversity
45
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
C+
+11
Exa
mple
#include
<iostream>
#include
<iterator>
#include
<vector>
#include
<algorithm>
int
main
()
{
std::vector<int>
v({10,
20,
30,
40});
for
(int
&i
:v)
std::cout
<<
i<<
std::endl;
auto
total
=0;
std::for_each
(v.begin
(),
v.end
(),
[&total](int
x){
total
+=
x;
});
std::cout
<<
total
<<
std::endl;
return
0;
}Van
derb
iltU
niversity
46
An
Overview
ofC+
+D
ouglas
C.Sch
mid
t
Sum
mary
•A
major
contrib
ution
ofC+
+is
itssu
pport
fordefi
nin
gab
stractdata
types
(AD
Ts)
&for
generic
programm
ing
–e.g.,
classes,param
eterizedtyp
es,&
exception
han
dlin
g
•For
some
systems,
C+
+’s
AD
Tsu
pport
ism
oreim
portan
tth
anusin
gth
eO
Ofeatu
resof
the
langu
age
•For
other
systems,
the
use
ofC+
+’s
OO
features
isessen
tialto
build
high
lyflexib
le&
extensib
lesoftw
are
–e.g.,
inheritan
ce,dyn
amic
bin
din
g,&
RT
TI
Van
derb
iltU
niversity
47