Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSCE 121-200 Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 18: Vectors, Templates and Exceptions 1.

Similar presentations


Presentation on theme: "CSCE 121-200 Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 18: Vectors, Templates and Exceptions 1."— Presentation transcript:

1 CSCE 121-200 Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 18: Vectors, Templates and Exceptions 1

2 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Changing Vector Size Ways to change the size of a vector v: v.push_back(7); v = v2; v.resize(10); // additional way 2

3 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Representing Vector Allocate extra space to accommodate future expansion class vector { int sz; // number of elements put in the vector double* elem; int space; // total amount of space allocated; // number of elements plus extra //... } 3 allocation:sz:  ------------elements-------  (initialized)  -----free space--------------  (uninitialized) 0

4 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Idea of Vector Resizing Add a function called reserve that handles space allocation – calls new to get new space – copies elements from old space to new space – deletes old space Function resize calls reserve Function push_back calls reserve if out of space to double the amount of space 4

5 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Vector’s Reserve Function void vector::reserve(int newalloc) // make the vector have space for newalloc elements { if (newalloc <= space) return; // never decrease allocation double* p = new double[newalloc]; // get space for (int i=0; i < sz; ++i) // copy old elements p[i] = elem[i]; delete[] elem; elem = p; // swing pointer space = newalloc; // update space } 5

6 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Vector’s Resize Function void vector::resize(int newsize) // make the vector have newsize elements; // initialize each new element with default value 0.0 { reserve(newsize); // make sure we have enough space for (int i = sz; i < newsize; ++i) elem[i] = 0; // initialize new elements sz = newsize; // update size } 6

7 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Vector’s Push_back Function void vector::push_back(double d) // increase vector size by one; // initialize new element with d { if (sz == 0) // no space; grab some reserve(8); else if (sz == space) // no more free space reserve(2*space); // get double the old space elem[sz] = d; // add d to the end ++sz; // increase the size } 7

8 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Optimizing Copy Assignment Remember copy assignment for vector? To assign vector a to vector v: – allocate a new array the size of a’s array – copy elements from a’s array to the new array – delete v’s current array – update sz and elem for v Now that we keep extra space to grow into, we can avoid the copying if v’s array is big enough to hold a’s elements 8

9 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Optimizing Copy Assignment 9 sz: a: v: To assign a to v, if a.sz is less than or equal to v.space, just copy a’s elements into v’s array

10 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Optimized Vector Copy Assignment vector& vector::operator=(const vector& a) { if (this==&a) return *this; // self-assignment, no work needed if (a.sz <= space) { // enough space, no need for new allocation for (int i = 0; i < a.sz; ++i) elem[i] = a.elem[i]; sz = a.sz; return *this; } // new allocation needed; mostly as in old version double* p = new double[a.sz]; for (int i = 0; i < a.sz; ++i) p[i] = a.elem[i]; delete[] elem; sz = a.sz; space = a.sz; // not in old version elem = p; return *this; } 10

11 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Templates The current vector we have built holds doubles We don’t want to rewrite the code for vector every time we want a vector of some other type We want to make the element type a parameter to vector – should handle both built-in types and user-defined types C++ provides a mechanism for us to do this, called “templates” 11

12 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Templates We can define types that take other types as parameters – type definitions can also take integers as parameters We can also define functions that take types as parameters This is the basis for generic programming in C++ – sometimes called “parametric polymorphism” – provides flexibility and performance 12

13 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Templated Class Example Define a class whose definition takes a type and an integer as parameters a Buffer that holds a certain number (N) of objects of a certain type (T) template class Buffer { /* … */ }; To make an object of type Buffer, you must give specific values for T and N: Buffer buf; // holds 1024 chars 13

14 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Templated Function Example Define a function that works on Buffer objects – since Buffer is templated, the function needs to be also template void fill(Buffer & b) { /* declare and use objects of type T, etc. */ } To instantiate the fill function, just call it with the appropriate Buffer object; compiler deduces the template arguments fill(buf); // here T is char and N is 1024 because // that’s what buf has 14

15 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Parameterize Vector with Element Type template class vector { //... }; //... vector vd; // T is double vector vi; // T is int vector > vvi; // T is vector vector vpd; // T is double* 15

16 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Vector of Doubles class vector { int sz; double* elem; int space; public: vector : sz(0), elem(0), space(0) {} explicit vector(int s) : sz(s), elem(new double[s]), space(s) {} vector(const vector&); vector& operator=(const vector&); ~vector() { delete[] elem; } double& operator[] (int n) { return elem[n]; } int size() const { return sz; } // resize, push_back, reserve, capacity... }; 16

17 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Vector of Chars class vector { int sz; char* elem; int space; public: vector : sz(0), elem(0), space(0) {} explicit vector(int s) : sz(s), elem(new char[s]), space(s) {} vector(const vector&); vector& operator=(const vector&); ~vector() { delete[] elem; } char& operator[] (int n) { return elem[n]; } int size() const { return sz; } // resize, push_back, reserve, capacity... }; 17

18 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Vector of T’s (Parameterized) template class vector { int sz; T* elem; int space; public: vector : sz(0), elem(0), space(0) {} explicit vector(int s) : sz(s), elem(new T[s]), space(s) {} vector(const vector&); vector& operator=(const vector&); ~vector() { delete[] elem; } T& operator[] (int n) { return elem[n]; } int size() const { return sz; } // resize, push_back, reserve, capacity... }; 18

19 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Templates Problems: – poor error diagnostics (but improving) – delayed error messages (often at link time) – all templates must be fully defined in each translation unit (so put them in header files) Recommendation: – use template-based libraries (e.g., vector) – don’t try to do anything fancy yourself (yet) 19

20 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Range Checking in Vector We can throw an exception: struct out_of_range { /*... */ }; template class vector { //... T& operator[](int n) { if (n < 0 || sz <= n) throw out_of_range(); return elem[n]; } }; 20

21 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Issues with Exceptions If we do use exceptions to report errors, we must ensure that it – doesn’t introduce new sources of errors – doesn’t complicate the code – doesn’t lead to resource leaks 21

22 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Example of Exception Leading to Resource Leak void suspicious(vector vd, int n) { int* p = new int[n]; // acquire memory //... vd[n] = 10; // might be out of range //... delete[] p; // release memory } If n is out of range for vd, then exception is thrown and p is not deleted! 22

23 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions How to Fix this Problem? Attempt 1: catch exception inside the function, do the delete of p, and then rethrow the exception – messy and ugly Attempt 2: don’t create objects with new; only have new inside constructors, and delete inside destructors – rely on scoping to avoid 23

24 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Functions that Create Objects Traditional way: return a pointer to the created object vector * make_vec() { vector ; // fill the vector with data return p; } But now user must remember to delete; if forgets, memory leak! 24

25 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Functions that Create Objects C++11 has an improvement (std::unique_ptr) that avoids the necessity of user calling delete – making a unique_ptr still requires the use of new C++14 has a further improvement (std::make_unique) which is used to make the unique_ptr and avoids the necessity of user explicitly calling new Just FYI 25

26 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Functions that Create Objects Best solution is don’t mess with pointers at all, instead return the object vector make_vec() { vector res; //...fill the vector return res; // move constructor makes // this efficient } 26

27 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions RAII: Resource Acquisition is Initialization Vector: – acquires memory for elements in constructor – manages the memory (changes size, controls access, etc. – releases the memory in destructor Special case of a general resource management strategy called RAII – also called “scoped resource management” – use it whenever you can – simple and cheap – interacts nicely with exceptions 27

28 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions A Confession standard library vector does not guarantee range checking we’ve been using a debug version in std_lib_facilities_4.h some standard library versions do check, though 28

29 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions To Get Guaranteed Range Checking in Vector use function member “at” instead of [ ] T& at(int n) { // checked access if (n < 0 || sz <= n) throw out_of_range(); return elem[n]; } T& operator[](int n) { // unchecked access return elem[n]; } 29

30 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Why Not Guarantee Checking? Checking costs a bit in speed and code size Some projects need optimal performance – huge data and/or tiny computing resources Standard must serve everyone – you can build checked on top of unchecked but not vice versa Some projects are not allowed to use exceptions – e.g., hard real-time constraints, high reliability 30

31 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions A Final Word About Implementing Vector: const Remember we can declare a variable (or parameter) as const If so, then we can only call functions on that object that are guaranteed not to change it Thus we need “const” versions of the accessors (at and operator[]) as well as non-const versions of them, so that we *can* change non-const vectors 31

32 CSCE 121:509-512 Set 18: Vectors, Templates and Exceptions Acknowledgments Photo on title slide: Layered Paper Owl Templates 3 by Tina D, license CC BY 2.0Layered Paper Owl Templates 3 Tina DCC BY 2.0 Slides are based on those for the textbook: http://www.stroustrup.com/Programming/19_vector.ppt 32


Download ppt "CSCE 121-200 Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 18: Vectors, Templates and Exceptions 1."

Similar presentations


Ads by Google