chapter 19 vectors, templates, and exceptions bjarne stroustrup

32
Chapter 19 Chapter 19 Vectors, templates, and Vectors, templates, and exceptions exceptions Bjarne Stroustrup Bjarne Stroustrup www.stroustrup.com/Programming www.stroustrup.com/Programming

Upload: chase-newman

Post on 26-Mar-2015

250 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Chapter 19Chapter 19Vectors, templates, and exceptionsVectors, templates, and exceptions

Bjarne StroustrupBjarne Stroustrupwww.stroustrup.com/Programmingwww.stroustrup.com/Programming

Page 2: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

OverviewOverview

Vector revisitedVector revisited How are they implemented?How are they implemented?

Pointers and free storePointers and free store DestructorsDestructors Copy constructor and copy assignmentCopy constructor and copy assignment ArraysArrays Array and pointer problemsArray and pointer problems Changing sizeChanging size

resize() and push_back()resize() and push_back() TemplatesTemplates Range checking and exceptionsRange checking and exceptions

33Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 3: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Changing vector sizeChanging vector size

Fundamental problem addressedFundamental problem addressed We (humans) want abstractions that can change size (We (humans) want abstractions that can change size (e.g.e.g., a vector , a vector

where we can change the number of elements). However, in computer where we can change the number of elements). However, in computer memory everything must have a fixed size, so how do we create the memory everything must have a fixed size, so how do we create the illusion of change? illusion of change?

GivenGivenvector v(n);vector v(n); // // v.size()==nv.size()==n

we can change its size in three wayswe can change its size in three ways Resize itResize it

v.resize(10);v.resize(10); // // vv now has now has 1010 elements elements

Add an elementAdd an element v.push_back(7);v.push_back(7); //// add an elementadd an element with the value with the value 77 to the end of to the end of

vv// // v.size() v.size() increases byincreases by 1 1

Assign to itAssign to it v = v2;v = v2; // // v v is now a copy ofis now a copy of v2 v2

// // v.size() v.size() now equalsnow equals v2.size() v2.size() 44Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 4: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Representing vectorRepresenting vector If youIf you resize() resize() or or push_back() push_back() once, you’ll probably do it again;once, you’ll probably do it again;

let’s prepare for that by sometimes keeping a bit of free space for future expansionlet’s prepare for that by sometimes keeping a bit of free space for future expansion

class vector {class vector {int sz;int sz;double* elem;double* elem;int space;int space; // // number of elements plus “free space”number of elements plus “free space”

// // (the number of “slots” for new elements)(the number of “slots” for new elements)public:public:

// // ……};};

55

allocation:sz:

------------elements------- (initialized)

-----free space-------------- (uninitialized)

0

Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 5: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Representing vectorRepresenting vector

An empty vector (no free store use):An empty vector (no free store use):

A vector(N) (no free space):A vector(N) (no free space):

66

N:0

Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 6: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

vector::reserve()vector::reserve() First deal with space (allocation); given space all else is easyFirst deal with space (allocation); given space all else is easy

Note: Note: reserve() reserve() doesn’t mess with size or element valuesdoesn’t mess with size or element values

void vector::reserve(int newalloc)void vector::reserve(int newalloc)// // make the vector have space formake the vector have space for newalloc newalloc elementselements

{{if (newalloc<=space) return;if (newalloc<=space) return; // // never decrease allocationnever decrease allocationdouble* p = new double[newalloc];double* p = new double[newalloc]; // // allocate new spaceallocate new spacefor (int i=0; i<sz; ++i) p[i]=elem[i];for (int i=0; i<sz; ++i) p[i]=elem[i]; // // copy old elementscopy old elementsdelete[ ] elem;delete[ ] elem; // // deallocate old spacedeallocate old spaceelem = p;elem = p;space = newalloc;space = newalloc;

}}

77Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 7: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

vector::resize()vector::resize() Given Given reserve()reserve(), , resize() resize() is easyis easy

reserve() reserve() deals with space/allocationdeals with space/allocation resize() resize() deals with element valuesdeals with element values

void vector::resize(int newsize)void vector::resize(int newsize)// // make the vector havemake the vector have newsize newsize elementselements// // initialize each new element with the default value 0.0initialize each new element with the default value 0.0

{{reserve(newsize);reserve(newsize); // // make sure we have sufficient spacemake sure we have sufficient spacefor(int i = sz; i<newsize; ++i) elem[i] = 0;for(int i = sz; i<newsize; ++i) elem[i] = 0; // // initialize new elementsinitialize new elementssz = newsize;sz = newsize;

}}

88Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 8: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

vector::push_back()vector::push_back()

Given Given reserve()reserve(), , push_back() push_back() is easyis easy reserve() reserve() deals with space/allocationdeals with space/allocation push_back() push_back() just adds a valuejust adds a value

void vector::push_back(double d)void vector::push_back(double d)// // increaseincrease vector sizevector size by oneby one// // initialize the new element withinitialize the new element with d d

{{if (sz==0) if (sz==0) // // no space: grab someno space: grab some

reserve(8);reserve(8);else if (sz==space) else if (sz==space) // // no more free space:no more free space: get more spaceget more space

reserve(2*space);reserve(2*space);elem[sz] = d;elem[sz] = d; // // add add dd at end at end++sz;++sz; // // and increase the size (and increase the size (sz sz is the number of elements)is the number of elements)

}}

99Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 9: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

resize() and push_back()resize() and push_back()

class vector {class vector { // // an almost realan almost real vector vector of of doubledoublessint sz;int sz; // // the sizethe sizedouble* elem;double* elem; // // a pointer to the elementsa pointer to the elementsint space;int space; // // size+free_spacesize+free_space

public:public:vector() : sz(0), elem(0), space(0) { }vector() : sz(0), elem(0), space(0) { } // // defaultdefault constructorconstructorexplicit vector(int s) :sz(s), elem(new double[s]) , space(s) { }explicit vector(int s) :sz(s), elem(new double[s]) , space(s) { } // // constructorconstructorvector(const vector&);vector(const vector&); //// copy constructorcopy constructorvector& operator=(const vector&);vector& operator=(const vector&); //// copy assignmentcopy assignment~vector() { delete[ ] elem; }~vector() { delete[ ] elem; } //// destructordestructor

double& operator[ ](int n) { return elem[n]; } double& operator[ ](int n) { return elem[n]; } // // access: return referenceaccess: return referenceint size() const { return sz; }int size() const { return sz; } // // current sizecurrent size

void resize(int newsize);void resize(int newsize); // // grow (or shrink)grow (or shrink)void push_back(double d);void push_back(double d); // // add elementadd element

void reserve(int newalloc);void reserve(int newalloc); // // get more spaceget more spaceint capacity() const { return space; }int capacity() const { return space; } // // current available spacecurrent available space

};}; 1010Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 10: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

The The thisthis pointer pointer A vector is an objectA vector is an object

vector v(10);vector v(10); vector* p = &v;vector* p = &v; //// we can point to a we can point to a vectorvector object object

Sometimes, Sometimes, vectorvector’s member functions need to refer to that object’s member functions need to refer to that object The name of that “pointer to self” in a member function is The name of that “pointer to self” in a member function is thisthis

1111

0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.00.0 0.0

10v:

this:

10

p:

Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 11: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

The The thisthis pointer pointervector& vector::operator=(const vector& a)vector& vector::operator=(const vector& a)

// // like copy constructor, but we must deal with old elementslike copy constructor, but we must deal with old elements{{

// // ……return *this;return *this; // // by convention,by convention,

// // assignment returns a reference to its object:assignment returns a reference to its object: *this *this}}

void f(vector v1, vector v2, vector v3)void f(vector v1, vector v2, vector v3){{

// // ……v1 = v2 = v3;v1 = v2 = v3; // // rare use made possible by rare use made possible by operator=()operator=() returning returning *this*this// // ……

}}

The The thisthis pointer has uses that are less obscure pointer has uses that are less obscure one of which we’ll get to in two minutesone of which we’ll get to in two minutes

1212Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 12: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

AssignmentAssignment

Copy and swap is a powerful general ideaCopy and swap is a powerful general idea

vector& vector::operator=(const vector& a)vector& vector::operator=(const vector& a)// // like copy constructor, but we must deal with old elementslike copy constructor, but we must deal with old elements// // make a copy of make a copy of aa then replace the current then replace the current szsz and and elemelem with with aa’s’s

{{double* p = new double[a.sz];double* p = new double[a.sz]; // // allocate new spaceallocate new spacefor (int i = 0; i<a.sz; ++i) p[i] = a.elem[i];for (int i = 0; i<a.sz; ++i) p[i] = a.elem[i]; // // copy elementscopy elementsdelete[ ] elem;delete[ ] elem; // // deallocate old spacedeallocate old spacesz = a.sz;sz = a.sz; // // set new sizeset new sizeelem = p;elem = p; // // set new elementsset new elementsreturn *this; return *this; //// return a self-referencereturn a self-reference

}}

1313Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 13: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Optimize assignmentOptimize assignment

““Copy and swap” is the most general ideaCopy and swap” is the most general idea but not always the most efficientbut not always the most efficient What if there already is sufficient space in the target vector?What if there already is sufficient space in the target vector?

Then just copy!Then just copy! For example: For example: a = b;a = b;

1414

sz:

sz:

b:

a:

Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 14: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Optimized assignmentOptimized assignment

vector& vector::operator=(const vector& a)vector& vector::operator=(const vector& a){{

if (this==&a) return *this;if (this==&a) return *this; // // self-assignment, no work neededself-assignment, no work needed

if (a.sz<=space) {if (a.sz<=space) { // // enough space,enough space, no need for new allocationno need for new allocationfor (int i = 0; i<a.sz; ++i) elem[i] = a.elem[i];for (int i = 0; i<a.sz; ++i) elem[i] = a.elem[i]; // // copy elementscopy elementsspace += sz-a.sz;space += sz-a.sz; // // increase free spaceincrease free spacesz = a.sz;sz = a.sz;return *this;return *this;

}}

double* p = new double[a.sz];double* p = new double[a.sz]; // // copy and swapcopy and swapfor (int i = 0; i<a.sz; ++i) p[i] = a.elem[i];for (int i = 0; i<a.sz; ++i) p[i] = a.elem[i];delete[ ] elem;delete[ ] elem;sz = a.sz;sz = a.sz;space = a.sz;space = a.sz;elem = p;elem = p;return *this; return *this;

}}1515Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 15: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

TemplatesTemplates But we don’t just want vector of doubleBut we don’t just want vector of double We want vectors with element types we specifyWe want vectors with element types we specify

vector<double>vector<double> vector<int>vector<int> vector<Month>vector<Month> vector<Record*>vector<Record*> // // vector of pointersvector of pointers vector< vector<Record> >vector< vector<Record> > // // vector of vectorsvector of vectors vector<char>vector<char>

We must make the element type a parameter to We must make the element type a parameter to vectorvector vector vector must be able to take both built-in types and user-must be able to take both built-in types and user-

defined types as element typesdefined types as element types This is not some magic reserved for the compiler, we can This is not some magic reserved for the compiler, we can

define our own parameterized types, called “templates”define our own parameterized types, called “templates”

1616Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 16: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

TemplatesTemplates The basis for generic programming in C++The basis for generic programming in C++

Sometimes called “parametric polymorphism”Sometimes called “parametric polymorphism” Parameterization of types (and functions) by types (and integers)Parameterization of types (and functions) by types (and integers)

Unsurpassed flexibility and performanceUnsurpassed flexibility and performance Used where performance is essential (Used where performance is essential (e.g.,e.g., hard real time and numerics) hard real time and numerics) Used where flexibility is essential (Used where flexibility is essential (e.g.,e.g., the C++ standard library) the C++ standard library)

Template definitionsTemplate definitionstemplate<class T, int N> class Buffer { /* template<class T, int N> class Buffer { /* …… */ };*/ };template<class T, int N> void fill(Buffer<T,N>& b) { /* template<class T, int N> void fill(Buffer<T,N>& b) { /* …… */ }*/ }

Template specializations (instantiations)Template specializations (instantiations)// // for a class template, you specify the template arguments:for a class template, you specify the template arguments:Buffer<char,1024> buf;Buffer<char,1024> buf; // // forfor buf, T buf, T is is char char andand N N isis 1024 1024

// // for a function template, the compiler deduces the template arguments:for a function template, the compiler deduces the template arguments:fill(buf);fill(buf); // // forfor fill(), T fill(), T is is char char andand N N isis 1024; 1024; that’s what that’s what buf buf hashas

1717Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 17: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Parameterize with element typeParameterize with element type

// // an almost realan almost real vector vector of of TTss::template<class T> class vector {template<class T> class vector {

// // ……};};

vector<double> vd;vector<double> vd; // // TT is is doubledoublevector<int> vi;vector<int> vi; // // T T isis int intvector< vector<int> > vvi;vector< vector<int> > vvi; // // T T is is vector<int>vector<int>

// // in whichin which T T isis int intvector<char> vc;vector<char> vc; // // TT is is char charvector<double*> vpd;vector<double*> vpd; // // T T is is double*double*vector< vector<double>* > vvpd;vector< vector<double>* > vvpd; // // T T isis vector<double>* vector<double>*

// // in whichin which T T is is doubledouble

1818Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 18: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Basically, Basically, vector<double>vector<double> is is

// // an almost realan almost real vector vector of of doubledoubles:s:class vector {class vector {

int sz;int sz; // // the sizethe sizedouble* elem;double* elem; // // a pointer to the elementsa pointer to the elementsint space;int space; // // size+free_spacesize+free_space

public:public:vector() : sz(0), elem(0), space(0) { }vector() : sz(0), elem(0), space(0) { } // // defaultdefault constructorconstructorexplicit vector(int s) :sz(s), elem(new double[s]), space(s) { } // explicit vector(int s) :sz(s), elem(new double[s]), space(s) { } // constructorconstructorvector(const vector&);vector(const vector&); //// copy constructorcopy constructorvector& operator=(const vector&);vector& operator=(const vector&); //// copy assignmentcopy assignment~vector() { delete[ ] elem; }~vector() { delete[ ] elem; } //// destructordestructor

double& operator[ ] (int n) { return elem[n]; }double& operator[ ] (int n) { return elem[n]; } // // access: return access: return referencereferenceint size() const { return sz; }int size() const { return sz; } // // the current sizethe current size

// …// …};}; 1919Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 19: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Basically, Basically, vector<char>vector<char> is is

// // an almost realan almost real vector vector of of charchars:s:class vector {class vector {

int sz;int sz; // // the sizethe sizechar* elem;char* elem; // // a pointer to the elementsa pointer to the elementsint space;int space; // // size+free_spacesize+free_space

public:public:vector() : sz(0), elem(0), space(0) { }vector() : sz(0), elem(0), space(0) { } // // defaultdefault constructorconstructorexplicit vector(int s) :sz(s), elem(new char[s]), space(s) { } // explicit vector(int s) :sz(s), elem(new char[s]), space(s) { } // constructorconstructorvector(const vector&);vector(const vector&); //// copy constructorcopy constructorvector& operator=(const vector&);vector& operator=(const vector&); //// copy assignmentcopy assignment~vector() { delete[ ] elem; }~vector() { delete[ ] elem; } //// destructordestructor

char& operator[ ] (int n) { return elem[n]; }char& operator[ ] (int n) { return elem[n]; } // // access: return access: return referencereferenceint size() const { return sz; }int size() const { return sz; } // // the current sizethe current size

// // ……};};

2020Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 20: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Basically, Basically, vector<T>vector<T> is is

// // an almost realan almost real vector vector of of TTss::template<class T> class vector {template<class T> class vector { // // read “for all types T” (just like in read “for all types T” (just like in

math)math)int sz;int sz; // // the sizethe sizeT* elem;T* elem; // // a pointer to the elementsa pointer to the elementsint space;int space; // // size+free_spacesize+free_space

public:public:vector() : sz(0), elem(0), space(0);vector() : sz(0), elem(0), space(0); // // default constructordefault constructorexplicit vector(int s) :sz(s), elem(new T[s]), space(s) { }explicit vector(int s) :sz(s), elem(new T[s]), space(s) { } //// constructorconstructorvector(const vector&);vector(const vector&); //// copy constructorcopy constructorvector& operator=(const vector&);vector& operator=(const vector&); //// copy assignmentcopy assignment~vector() { delete[ ] elem; }~vector() { delete[ ] elem; } //// destructordestructor

T& operator[ ] (int n) { return elem[n]; } T& operator[ ] (int n) { return elem[n]; } // // access: return referenceaccess: return referenceint size() const { return sz; }int size() const { return sz; } // // the current sizethe current size

// // ……};}; 2121Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 21: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

TemplatesTemplates Problems (“there’s no free lunch”)Problems (“there’s no free lunch”)

Poor error diagnosticsPoor error diagnostics Often spectacularly poorOften spectacularly poor

Delayed error messagesDelayed error messages Often at link timeOften at link time

All templates must be fully defined in each translation unitAll templates must be fully defined in each translation unit (the facility for separate compilation of templates,(the facility for separate compilation of templates,

called “export”, is not widely available) called “export”, is not widely available) So place template definitions in header filesSo place template definitions in header files

RecommendationRecommendation Use template-based librariesUse template-based libraries

Such as the C++ standard librarySuch as the C++ standard library E.g.,E.g., vectorvector, , sort()sort() Soon to be described in some detailSoon to be described in some detail

Initially, write only very simple templates yourselfInitially, write only very simple templates yourself Until you get more experienceUntil you get more experience

2222Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 22: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Range checkingRange checking

// // an almost realan almost real vector vector of of TTs:s:

struct out_of_range { /* struct out_of_range { /* …… */ }; */ };

template<class T> class vector {template<class T> class vector {// // ……T& operator[ ](int n);T& operator[ ](int n); // // accessaccess// // ……

}; };

template<class T> template<class T> T& vector<T>::operator[ ](int n)T& vector<T>::operator[ ](int n){{

if (n<0 || sz<=n) throw out_of_range();if (n<0 || sz<=n) throw out_of_range();return elem[n];return elem[n];

}}

2323Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 23: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Range checkingRange checking

void fill_vec(vector<int>& v, int n)void fill_vec(vector<int>& v, int n) // // initialize initialize v v with factorialswith factorials{{

for (int i=0; i<n; ++i) v.push_back(factorial(i));for (int i=0; i<n; ++i) v.push_back(factorial(i));}}

int main()int main(){{

vector<int> v;vector<int> v;try {try {

fill_vec(v,10);fill_vec(v,10);for (int i=0; i<=v.size(); ++i)for (int i=0; i<=v.size(); ++i)

cout << "v[" << i << "]==" << v[i] << '\n';cout << "v[" << i << "]==" << v[i] << '\n';}}catch (out_of_range) {catch (out_of_range) { // // we’ll get here (why?)we’ll get here (why?)

cout << "out of range error";cout << "out of range error";return 1;return 1;

}}}}

2424Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 24: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Exception handling Exception handling (primitive)(primitive)

// // sometimes we cannot do a complete cleanupsometimes we cannot do a complete cleanup

vector<int>* some_function()vector<int>* some_function() // // make a filledmake a filled vector vector{{

vector<int>* p = new vector<int>;vector<int>* p = new vector<int>; // // we allocate on free store,we allocate on free store,// // someone must deallocatesomeone must deallocate

try {try {fill_vec(*p,10);fill_vec(*p,10);// // ……return p;return p; // // all’s well; return the filled vectorall’s well; return the filled vector

}}catch (…) {catch (…) {

delete p;delete p; // // do our local cleanupdo our local cleanupthrow;throw; // // re-throw to allow our caller to deal re-throw to allow our caller to deal

}}}}

2525Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 25: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Exception handling Exception handling (simpler and more structured)(simpler and more structured)

// // When we use scoped variables cleanup is automaticWhen we use scoped variables cleanup is automatic

vector<int> glob;vector<int> glob;

void some_other_function()void some_other_function() // // make a filledmake a filled vector vector{{

vector<int> v;vector<int> v; // // note: vector handles the deallocation of elementsnote: vector handles the deallocation of elements

fill_vec(v,10);fill_vec(v,10);// // use vuse vfill_vec(glob,10);fill_vec(glob,10);// // ……

}}

if you feel that you need a try-block: think.if you feel that you need a try-block: think. You might be able to do without itYou might be able to do without it

2626Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 26: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

RAII RAII (Resource Acquisition Is Initialization)(Resource Acquisition Is Initialization)

VectorVector acquires memory for elements in its constructoracquires memory for elements in its constructor Manage it (changing size, controlling access, etc.)Manage it (changing size, controlling access, etc.) Gives back (releases) the memory in the destructorGives back (releases) the memory in the destructor

This is a special case of the general resource management This is a special case of the general resource management strategy called RAIIstrategy called RAII Also called “scoped resource management”Also called “scoped resource management” Use it wherever you canUse it wherever you can It is simpler and cheaper than anything elseIt is simpler and cheaper than anything else It interacts beautifully with error handling using exceptionsIt interacts beautifully with error handling using exceptions Examples of “resources”:Examples of “resources”:

Memory, file handles, sockets, I/O connections (iostreams handle those using RAII), Memory, file handles, sockets, I/O connections (iostreams handle those using RAII), locks, widgets, threads.locks, widgets, threads.

2727Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 27: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

A confessionA confession

The standard library The standard library vectorvector doesn’t guarantee range checking of doesn’t guarantee range checking of [ ][ ]

You have been usingYou have been using EitherEither our debug version, called our debug version, called VectorVector, which does check, which does check OrOr a standard library version that does check (several do) a standard library version that does check (several do)

Unless your version of the standard library checks, we “cheated”Unless your version of the standard library checks, we “cheated” In In std_lib_facilities.hstd_lib_facilities.h, we use the nasty trick (a macro substitution) of , we use the nasty trick (a macro substitution) of

redefining redefining vectorvector to mean to mean VectorVector#define vector Vector#define vector Vector ((This trick is nasty because what you see looking at the code is not This trick is nasty because what you see looking at the code is not

what compiler sees – in real code macros are a significant source of what compiler sees – in real code macros are a significant source of obscure errors)obscure errors)

We did the same for We did the same for stringstring

2828Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 28: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

What the standard guaranteesWhat the standard guarantees// // the standard library vector doesn’t guarantee a range check in the standard library vector doesn’t guarantee a range check in operator[ ]operator[ ]::template<class T> class vector {template<class T> class vector {

// …// …T& at(int n);T& at(int n); //// checked accesschecked accessT& operator[ ](int n);T& operator[ ](int n); // // unchecked accessunchecked access

}; };

template<class T> template<class T> T& vector<T>::at (int n)T& vector<T>::at (int n){{

if (n<0 || sz<=n) throw out_of_range();if (n<0 || sz<=n) throw out_of_range();return elem[n];return elem[n];

}}

template<class T> template<class T> T& vector<T>::operator[ ](int n)T& vector<T>::operator[ ](int n){{

return elem[n];return elem[n];}} 2929Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 29: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

What the standard guaranteesWhat the standard guarantees Why doesn’t the standard guarantee checking?Why doesn’t the standard guarantee checking?

Checking cost in speed and code sizeChecking cost in speed and code size Not much; don’t worryNot much; don’t worry

No student project needs to worryNo student project needs to worry Few real-world projects need to worryFew real-world projects need to worry

Some projects need optimal performanceSome projects need optimal performance Think huge (e.g., Google) and tiny (e.g., cell phone)Think huge (e.g., Google) and tiny (e.g., cell phone)

The standard must serve everybodyThe standard must serve everybody You can build checked on top of optimalYou can build checked on top of optimal You can’t build optimal on top of checkedYou can’t build optimal on top of checked

Some projects are not allowed to use exceptionsSome projects are not allowed to use exceptions Old projects with pre-exception partsOld projects with pre-exception parts High reliability, hard-real-time code (think airplanes)High reliability, hard-real-time code (think airplanes)

3030Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 30: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Access to const vectorsAccess to const vectors

template<class T> class vector {template<class T> class vector {// …// …T& at(int n);T& at(int n); //// checked accesschecked accessconst T& at(int n) const;const T& at(int n) const; //// checked accesschecked access

T& operator[ ](int n);T& operator[ ](int n); // // unchecked accessunchecked accessconst T& operator[ ](int n) const;const T& operator[ ](int n) const; // // unchecked accessunchecked access// // ……

}; };

void f(const vector<double> cvd, vector<double> vd)void f(const vector<double> cvd, vector<double> vd){{

// // ……double d1 = cvd[7];double d1 = cvd[7]; // // call thecall the const const version ofversion of [ ] [ ]double d2 = vd[7];double d2 = vd[7]; //// call the non-call the non-constconst version of version of [ ][ ]cvd[7] = 9;cvd[7] = 9; // // error: call theerror: call the const const version of [ ]version of [ ]vd[7] = 9;vd[7] = 9; // // call thecall the non-non-const const version of [ ]: okversion of [ ]: ok

}} 3131Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

Page 31: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

StringString

A A stringstring is rather similar to a vector<char> is rather similar to a vector<char> E.g. E.g. size(), [ ], push_back()size(), [ ], push_back() Built with the same language features and techniquesBuilt with the same language features and techniques

A A stringstring is optimized for character string manipulation is optimized for character string manipulation Concatenation (Concatenation (++)) Can produce C-style string (Can produce C-style string (c_str()c_str())) >> input terminated by whitespace>> input terminated by whitespace

3232

6

H o w yd !

Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10

\0

Page 32: Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup

Next lectureNext lecture An introduction to the STL, the containers and An introduction to the STL, the containers and

algorithms part of the C++ standard library. algorithms part of the C++ standard library. Here we’ll meet sequences, iterators, and Here we’ll meet sequences, iterators, and containers (such as containers (such as vector, listvector, list, and , and mapmap). The ). The algorithms include algorithms include find()find(),, find_if() find_if(),, sort() sort(),, copy()copy(),, copy_if() copy_if(), and , and accumulate()accumulate()..

3333Stroustrup/Programming Apr'10Stroustrup/Programming Apr'10