ECE 449 OOP and Computer Simulation Lecture 08 Resource Management I

Size: px
Start display at page:

Download "ECE 449 OOP and Computer Simulation Lecture 08 Resource Management I"

Transcription

1 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/69 ECE 449 OOP and Computer Simulation Lecture 08 Resource Management I Professor Jia Wang Department of Electrical and Computer Engineering Illinois Institute of Technology October 13, 2017

2 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 2/69 Outline Object Composition and Exception Object Composition Exceptions Resource Management Resource Acquisition Is Initialization (RAII) Design Your Own Vector Class Flexible Memory Management Member Functions Efficient Updates Copy Control

3 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 3/69 Reading Assignment This lecture: 4.1, 11 Next lecture: Project 4 Specification

4 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 4/69 Outline Object Composition and Exception Object Composition Exceptions Resource Management Resource Acquisition Is Initialization (RAII) Design Your Own Vector Class Flexible Memory Management Member Functions Efficient Updates Copy Control

5 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 5/69 Outline Object Composition and Exception Object Composition Exceptions Resource Management Resource Acquisition Is Initialization (RAII) Design Your Own Vector Class Flexible Memory Management Member Functions Efficient Updates Copy Control

6 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 6/69 Object Composition Object composition: the method to compose larger objects from smaller ones E.g. a netlist object is consisting of many net and gate objects. So far we have seen two ways to compose an object. If we care about values, use a data member of type T or a container whose elements are of type T. If we care about objects themselves, use a data member of type T * or a container whose elements are of type T *, with the objects on the heap. Composition means ownership. When the parent object is constructed, the objects it holds should be constructed. When the parent object is destroyed, the objects it holds should be destroyed.

7 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 7/69 Object Composition Association Association: objects may interact with each other E.g. a net object interacts with multiple pin objects to decide what signal it should take. Associations are almost always implemented as pointers. However, association does not imply ownership. Never delete the pointers to the pin objects in the member container connections_ of a net object. Object composition or association? There are cases where it is difficult to tell one from the other so we need GC. Otherwise, it is still preferable in C++ to distinguish the two because ownership and lifetime matter for predictable performance.

8 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 8/69 Object Lifetime Management Recall there are two ways for object composition. 1. Objects that are member variables of the parent object Managed by the compiler automatically. Constructed before ctor body and destroyed after dtor body. E.g. the std::string members in various classes. 2. Objects on the heap owned by the parent object Managed by programmers through the ctors/dtor of the parent object. E.g. the net and gate objects in netlist. We need to learn how the compiler handles 1. in order to write correct code for 2.

9 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 9/69 Automatic Lifetime Management for Member Variables Member variables are constructed before any ctor body. They are constructed in the order they appear in the class definition. Programmers may specify how the members are constructed using the initializer list. The compiler will default initialize all the members whose constructions are not specified by programmers. Member variables are destroyed automatically after the dtor body. In the reversed order they appear in the class definition.

10 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 10/69 Outline Object Composition and Exception Object Composition Exceptions Resource Management Resource Acquisition Is Initialization (RAII) Design Your Own Vector Class Flexible Memory Management Member Functions Efficient Updates Copy Control

11 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 11/69 Motivations How to handle errors in ctors? Ctors cannot return results. How to enforce error handling? So far we always use the returned result of a function to indicate errors. However, it is up to the users of the function to verify whether there is any error. Users have reasons to ignore results from functions. It is quite tedious to verify results from every function calls. The code becomes much less readable if most of lines are dealing with errors and trying to resolve them. So invariants may be broken eventually and your program crashes.

12 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 12/69 Exceptions date::date(int y, int m, int d) : year(y), month(m), day(d) { if (!valid()) { throw std::runtime_error("invalid date"); Assume valid is a member function of date that returns whether year/month/day is a valid calendar date. Instead of returning the result of valid from the ctor, we notify the C++ implementation of the error by throwing an exception. You can throw an object of any type. Though in practice, people design different class types for different reasons of errors.

13 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 13/69 Standard Exception Types date::date(int y, int m, int d) : year(y), month(m), day(d) { if (!valid()) { throw std::runtime_error("invalid date"); std::runtime_error is a class type from the standard header stdexcept indicating an error at runtime. Recall that std::runtime_error("invalid date") constructs a std::runtime_error object with the argument "Invalid date". There are other standard exception types. As introduced in the textbook They are used by the standard library. You can also use them for your own program.

14 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 14/69 Use Exceptions to Replace Returns class date { public: void set(int y, int m, int d);... ; // class date void date::set(int y, int m, int d) { year = y; month = m; day = d; if (!valid()) { throw std::runtime_error("invalid date"); Usually, execution flow only need to report errors by throwing exceptions, and doesn t need to handle them. The readability of the code is improved since people no longer need to filter out error handling code when trying to understand the usual functionality.

15 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 15/69 Exception Handling void some_function() { date someday(2017, 2, 29);... // usual business flow bool do_business() { try { // usual business flow some_function(); another_function(); catch (std::exception &e) { std::cerr << e.what() << std::endl; return false; return true; Though you are forced to handle exceptions in your program, you don t need to handle them immediately. Improve readability by NOT flooding usual business flows with error handling codes If an exception is not handled, the program will abort.

16 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 16/69 Exceptions vs. Returned Results An exception that is not handled will be propagated automatically to the caller. You have to do that manually for results from functions. If an exception is not handled beyond main, the C++ implementation will handle it by aborting your program. A debugger can be used to identify the place such exception is thrown. If a result from a function indicating an error is not handled, most likely there will be undefined behavior. The most effective way to handle exceptions is to have a try-catch construct only when you know how to recover from the exception. E.g. have only one try-catch in main The exceptions are handled in a centralized manner. Otherwise, there is no advantage over returned results. You may choose to NOT handle exceptions at all.

17 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 17/69 Exceptions vs. Assertions Sometimes, it is hard to tell whether a violation of some condition is a violation of precondition or an error. Is passing an invalid combination of year/month/day to the ctor of date a violation of precondition or an error? Common practice: who causes the violation? If it is caused by programmers, e.g. because of typos or misunderstandings of function preconditions, use assertions. If it is caused by issues beyond programmer s control, e.g. invalid user inputs or network failures, use exceptions. It is still a design decision so there is no definite answer. You need to make your own trade-offs. Assertions may be turned off, making all checks useless. Check conditions and throw exceptions may affect the performance. An example: how std::vector handles out-of-range indices? [] uses assertions. The member function at will throw an exception.

18 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 18/69 Object Composition and Exception What happens to the parent object if an exception is thrown by a member ctor? Be aware that it is possible that some members are constructed and some are not.

19 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 19/69 Outline Object Composition and Exception Object Composition Exceptions Resource Management Resource Acquisition Is Initialization (RAII) Design Your Own Vector Class Flexible Memory Management Member Functions Efficient Updates Copy Control

20 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 20/69 Resource Management Resources: things with limited availability Memory File handles Network connections Database connections etc. Management: release a resource promptly Only when the resource was acquired successfully. After all the usages of the resource.

21 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 21/69 Resource management seems to be easy. void some_function() { FILE *fp = fopen("input_file", "r");... // do something with the file fclose(fp); Consider file operations in C. The file handle is acquired by fopen and released by fclose. A typical code sandwich: acquire use release.

22 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 22/69 Resource management could become complicated. // C-style resource management void some_function() { FILE *fp = fopen("input_file", "r"); if (...) {... fclose(fp); return; for (...) { if (...) {... else {... fclose(fp); return; fclose(fp); When there are many returns, the programmer is responsible to make sure the resource is always released.

23 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 23/69 The previous programs are WRONG! void some_function() { FILE *fp = fopen("input_file", "r"); another_function(fp); fclose(fp); If another_function throws an exception, fclose(fp); won t be executed. There will be resource leakage. A function in the call stack may allow the program to recover from the exception. However, you won t be able to release the file handle fp. It s lost.

24 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 24/69 Thinking of try-catch? void some_function() { FILE *fp = NULL; try { fp = fopen("input_file", "r"); another_function(fp); fclose(fp); catch (...) { if (fp!= NULL) fclose(fp); I should use finally as in many other languages. Though in C++ we don t have it since we don t need it. Those languages eventually learned from C++ so that finally is not needed in many cases nowadays.

25 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 25/69 Too complicated! // similar to Java resource management prior to Java 1.7 void some_function() { FILE *fp_in = NULL; FILE *fp_out = NULL; try { fp_in = fopen("input_file", "r"); do_something(fp_in); if (...) { fclose(fp_in); return; fp_out = fopen("output_file", "w"); do_something_else(fp_in, fp_out); for (...) {... if (...) { fclose(fp_out); fclose(fp_in); return; another_function(fp_out); fclose(fp_out); fclose(fp_in); catch (...) { if (fp_in!= NULL) fclose(fp_in); if (fp_out!= NULL) fclose(fp_out); When there are many returns and many resources. I can t guarantee the correctness of the above code since it is too complicated.

26 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 26/69 Outline Object Composition and Exception Object Composition Exceptions Resource Management Resource Acquisition Is Initialization (RAII) Design Your Own Vector Class Flexible Memory Management Member Functions Efficient Updates Copy Control

27 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 27/69 Resource Acquisition Is Initialization (RAII) void some_function() { std::ifstream fin("input_file"); do_something(fin); if (...) return; // fin destroyed std::ofstream fout("output_file"); do_something_else(fin, fout); for (...) {... if (...) return; // both fin and fout destroyed another_function(fout); // both fin and fout destroyed C++ makes programmer s life much easier via RAII. Leverage object lifetime for resource management (as adopted by many other languages). Use object composition to manage multiple resources. A resource is acquired when the object is constructed. The resource is released when the object is destroyed. We don t need to release fin and fout explicitly at every exit. What about exceptions?

28 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 28/69 Stack Unwinding void some_function() { std::ifstream fin("input_file"); do_something(fin); if (...) return; // fin destroyed std::ofstream fout("output_file"); do_something_else(fin, fout); for (...) {... if (...) return; // both fin and fout destroyed another_function(fout); // both fin and fout destroyed Local objects will be destroyed automatically whenever the function returns. Stack Unwinding: even when the function exits due to an unhandled exception. Since dtors may be called during exception handling, they SHOULD NEVER throw exceptions.

29 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 29/69 Object Lifetime Management with Exception How to design my own class for resource management via RAII? Objects that are member variables of the parent object What if a member construction throws an exception? Objects on the heap owned by the parent object Programmers should provide the same guarantee as the compiler provides automatically for the member variables.

30 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 30/69 Automatic Lifetime Management for Member Variables with Exception Member variables are constructed before any ctor body. In the order they appear in the class definition. Member are destroyed automatically after the dtor body. In the reversed order they appear in the class definition. If a ctor fails, i.e. throws an exception, compiler guarantees that, All or None: either the parent object is constructed successfully or none of the members got constructed. What if a dtor fails? Dtors should never fail you should not throw exceptions out of dtors.

31 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 31/69 Example I: The Classes struct will_not_throw { will_not_throw() {std::cout << "ctor of will_not_throw" << std::endl; ~will_not_throw() {std::cout << "dtor of will_not_throw" << std::endl; ; // struct will_not_throw class ctor_throw { will_not_throw wnt_; public: ctor_throw() { std::cout << "ctor of ctor_throw" << std::endl; throw std::runtime_error("from ctor of ctor_throw"); ~ctor_throw() {std::cout << "dtor of ctor_throw" << std::endl; ; // class ctor_throw Member functions can be declared and defined at the same time.

32 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 32/69 Example I: Parent Object on the Stack void some_function() { ctor_throw ct; void some_caller() { try { some_function(); catch (std::exception &e) { std::cout << e.what() << std::endl; The output ctor of will_not_throw ctor of ctor_throw dtor of will_not_throw from ctor of ctor_throw When the ctor of the parent object fails, the members are destroyed automatically. The dtor of the parent object will not be called since the object has not been constructed this is exactly what resource management needs!

33 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 33/69 Example I: Parent Object on the Heap void another_function() { ctor_throw *pct = new ctor_throw; void another_caller() { try { another_function(); catch (std::exception &e) { std::cout << e.what() << std::endl; The output is the same as in the previous slide. No memory leakage: when the construction fails, the piece of allocated memory is returned to the heap automatically.

34 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 34/69 Example II: The Classes struct will_throw { will_throw() { std::cout << "ctor of will_throw" << std::endl; throw std::runtime_error("from ctor of will_throw"); ~will_throw() {std::cout << "dtor of will_throw" << std::endl; ; // struct will_throw class member_throw { will_not_throw wnt_; will_throw wt_; public: member_throw() {std::cout << "ctor of member_throw" << std::endl; ~member_throw() {std::cout << "dtor of member_throw" << std::endl; ; // class member_throw

35 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 35/69 Example II: The Output void some_function() { member_throw mt; void some_caller() { try { some_function(); catch (std::exception &e) { std::cout << e.what() << std::endl; The output ctor of will_not_throw ctor of will_throw dtor of will_not_throw from ctor of will_throw When the ctor of a member fails, the members that are already constructed will be destroyed automatically. The body of the ctor of the parent object won t be executed. Same output if the parent object is created on the heap.

36 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 36/69 Outline Object Composition and Exception Object Composition Exceptions Resource Management Resource Acquisition Is Initialization (RAII) Design Your Own Vector Class Flexible Memory Management Member Functions Efficient Updates Copy Control

37 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 37/69 The Vec Class Vec<int> empty; // empty vector Vec<int> ones(100, 1); // vector of s for (size_t i = 0; i < ones.size(); ++i) { ones[i] = i; // access elements using [] for (Vec<int>::iterator it = ones.begin(); it!= ones.end(); ++it) { // iterators std::cout << *it << std::endl; Let s design a class Vec to learn how std::vector works. As a good example of how resource management should be done in any language. We usually design a class by specifying its interface first. So we follow the usual way std::vector is used.

38 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 38/69 Outline Object Composition and Exception Object Composition Exceptions Resource Management Resource Acquisition Is Initialization (RAII) Design Your Own Vector Class Flexible Memory Management Member Functions Efficient Updates Copy Control

39 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 39/69 Class Design // vec.h template <class T> class Vec { public: typedef T value_type; Vec(); Vec(size_t n, const value_type &val); private: value_type *data_; size_t n_; size_t capacity_; ; // class Vec<T> The member capacity_ indicates the number of elements that can be held in data_. The member n_ indicates the number of elements that are currently in data_.

40 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 40/69 Flexible Memory Management We need to keep two kinds of things in the array data_. data_[0],..., data_[n_-1] are initialized objects of type value_type as the elements. data_[n_],..., data_[capacity_-1] are not objects but bytes on the heap in other words, they are uninitialized and need to be constructed into objects. That s also the class invariant. Clearly new/delete cannot be used. We need language features/library functions to Determine how many memory bytes are required to hold a given number of objects Allocate that many bytes from the heap, uninitialized Construct individual objects on the uninitialized memory Destroy individual objects to make memory uninitialized Deallocate (release to the heap) the uninitialized memory

41 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 41/69 Memory Allocation Interface // vec.h template <class T> class Vec {... private:... static value_type *allocate(size_t n); static void deallocate(value_type *p); ; // class Vec<T> allocate should return a pointer to a piece of uninitialized memory that can hold n value_type object. deallocate should release the uninitialized memory pointed by p to the heap. Member functions should be declared static if they don t depend on any object of the class but are conceptually part of the class. Like usual functions, there is no implicit object parameter. Like member functions, they can access private members.

42 Memory Allocation // within class Vec<T> static value_type allocate(size_t n) { size_t num_of_bytes = sizeof(value_type)*n; void *p = ::operator new[](num_of_bytes); return (value_type *)p; For template classes, all members should be implemented within the class. The expression sizeof(t) returns the number of bytes an object of the type T consumes. The function operator new[] is used to allocate memory from the heap. For the standard header new When success, it returns a pointer to the memory. Otherwise, it throws std::bad_alloc. :: is used to emphasize it is from the global namespace. operator new[] has no idea what is the type of the objects the pointer it returns is of type void *. We need to convert it to a pointer to value_type objects. However, the memory remains uninitialized. ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 42/69

43 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 43/69 Memory Deallocation static void deallocate(value_type *p) { if (p == NULL) return; ::operator delete[](p); operator delete[] is used to release memory to the heap. Similarly, there are two functions operator new and operator delete. Moreover, as you may guess, The expression new T will call operator new to acquire the memory and then constructs the object. The expression delete p will destroy the object pointed by p and then call operator delete to release the memory. They have the same functionality as malloc and free in C.

44 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 44/69 Memory Initialization Interface private:... static void uninitialized_fill(value_type *uninit_b, value_type *uninit_e, const value_type &val); static void uninitialized_copy(const value_type *from_b, const value_type *from_e, value_type *uninit_b); We follow the standard library to create two static member functions for initializing a piece of memory into objects. uninitialized_fill will fill the uninitialized memory within the range [uninit_b, uninit_e) with objects having a value of val. uninitialized_copy will copy the objects within the range [from_begin, from_end) to the uninitialized memory pointed by uninit_b. It is programmers responsibility to ensure that piece of memory can hold enough number of objects.

45 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 45/69 Placement new static void uninitialized_fill(value_type *uninit_b, value_type *uninit_e, const value_type &val) { for (; uninit_b!= uninit_e; ++uninit_b) { new (uninit_b) value_type(val); The placement new statement new (p) T(args); is used to construct an object of type T on a piece of memory pointed by p, using arguments args. If you feel it s confusing, here is how to memorize the syntax: first, T(args) means to construct an object of type T using args; then new (p) means the object should be at the memory pointed by p. What if one construction throws an exception? Then we have no idea how many objects are actually constructed. Therefore we won t be able to destroy them, potential resource leakage!

46 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 46/69 Exception Safety for uninitialized fill static void uninitialized_fill(value_type *uninit_b, value_type *uninit_e, const value_type &val) { value_type *init_b = uninit_b; try { for (; uninit_b!= uninit_e; ++uninit_b) { new (uninit_b) value_type(val); catch (...) { // catch all exceptions for (; init_b!= uninit_b; ++init_b) { init_b->~value_type(); // call dtor to destroy the object throw; // re-throw the exception Postcondition of uninitialized_fill: All or None All the objects are initialized if the function returns normally. If some construction throws, then the function will throw the same exception and no object is initialized.

47 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 47/69 Implement uninitialized copy static void uninitialized_copy(const value_type *from_b, const value_type *from_e, value_type *uninit_b) { value_type *init_b = uninit_b; try { for (; from_b!= from_e; ++from_b, ++uninit_b) { new (uninit_b) value_type(*from_b); catch (...) { // catch all exceptions for (; init_b!= uninit_b; ++init_b) { init_b->~value_type(); // call dtor to destroy the object throw; // re-throw the exception Postcondition of uninitialized_copy: All or None

48 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 48/69 Implement Constructors and Destructor Vec() : data_(null), n_(0), capacity_(0) { Vec(size_t n, const value_type &val) : data_(allocate(n)), n_(n), capacity_(n) { try { uninitialized_fill(data_, data_+n_, val); catch (...) { deallocate(data_); throw; Vec::~Vec() { for (size_t i = 0; i < n_; ++i) { data_[i].~value_type(); deallocate(data_); If a ctor fail, the dtor won t be called automatically, so we need to deallocate the memory. The dtor of value_type should not throw.

49 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 49/69 Outline Object Composition and Exception Object Composition Exceptions Resource Management Resource Acquisition Is Initialization (RAII) Design Your Own Vector Class Flexible Memory Management Member Functions Efficient Updates Copy Control

50 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 50/69 Iterators template <class T> class Vec { public:... typedef value_type *iterator; typedef const value_type *const_iterator;... ; // class Vec<T> As the elements are stored in an array, pointers can be used as iterators for our container Vec. const_iterator: need a pointer pointing to const objects Type of pointers pointing to const objects of type T: const T * or equivalently T const * Is T * const a valid type? Yes, that s a const pointer: the pointer cannot be changed, but the object it points to can be changed.

51 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 51/69 Member Functions template <class T> class Vec { public:... size_t size() const {return n_; iterator begin() {return data_; iterator end() {return data_+n_; const_iterator begin() const {return data_; const_iterator end() const {return data_+n_;... ; // class Vec<T> Be aware of const and non-const member functions

52 Operator and Operator Overloading // some source file for (size_t i = 0; i < ones.size(); ++i) { ones[i] = i; // access elements using [] // vec.h template <class T> class Vec { public:... value_type &operator[](size_t i) { assert(i < n_); return data_[i];... ; // class Vec<T> The operator [] need to be defined for Vec so that the expression ones[i] makes sense. Operator overloading: when evaluating the expression ones[i], the compiler will attempt to translate it into the function call ones.operator[](i). You define what [] means for Vec by providing that member function, though you won t be able to call it directly. ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 52/69

53 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 53/69 Constness and Operators template <class T> class Vec { public:... const value_type &operator[](size_t i) const { assert(i < n_); return data_[i];... ; // class Vec<T> You should also provide a const operator[] for use with const Vec objects.

54 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 54/69 Outline Object Composition and Exception Object Composition Exceptions Resource Management Resource Acquisition Is Initialization (RAII) Design Your Own Vector Class Flexible Memory Management Member Functions Efficient Updates Copy Control

55 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 55/69 The reserve Function template <class T> class Vec { public:... void reserve(size_t cap);... ; // class Vec<T> We can make push_back even more efficient if the user can give us some hints on the number of the elements. The member function reserve should allocate enough memory to hold at least cap objects.

56 Implement reserve void reserve(size_t cap) { if (cap <= capacity_) return; // nothing to do if there is enough memory // prepare new memory/objects value_type *p = allocate(cap); try { uninitialized_copy(data_, data_+n, p); catch (...) { deallocate(p); throw; // get rid of old objects/memory for (size_t i = 0; i < n_; ++i) { data_[i].~value_type(); deallocate(data_); // update members data_ = p; capacity_ = cap; ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 56/69

57 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 57/69 Implement push back and pop back void push_back(const value_type &val) { if (n_ == capacity_) { reserve(std::max(n_+1, n_*2)); new (data_+n_) value_type(val); ++n_; void pop_back() { assert(n_ > 0); data_[n_-1].~value_type(); --n_; Each time when the container is full (n_ == capacity_), we need to reserve more memory. It has been proved if the capacity is increased by a fixed portion, then on average push_back will take O(1) time. Let s double it every time. We don t need to worry about exceptions since if something goes wrong, the dtor of Vec will take care of the elements and the memory.

58 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 58/69 Outline Object Composition and Exception Object Composition Exceptions Resource Management Resource Acquisition Is Initialization (RAII) Design Your Own Vector Class Flexible Memory Management Member Functions Efficient Updates Copy Control

59 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 59/69 Copy and Assignment Vec<int> a(100, 0); Vec<int> b = a; // make a copy Vec<int> c; c = a; // assignment Copy: construct an object as a copy of the existing one For Vec, elements should be constructed as a copy of those from the right-hand side (RHS). Assignment: change an object into a desired value For Vec, current elements should be destroyed and then be constructed as a copy of those from RHS. Copy Assignment Before copy, the object doesn t exist. Before assignment, the object is initialized.

60 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 60/69 Anything wrong? void some_function() { Vec<int> a(100, 0); Vec<int> b = a; // make a copy Vec<int> c; c = a; // assignment The program will compile. The compiler will generate code to handle copy and assignment. What s your expectation of the compiler? It is very unlikely the compiler knows the elements are stored on the heap and are managed by using data_ and n_. The compiler will simply make a copy of/assign the members. Members of a, b, c will have the same value. a.data_ will then be deallocated three times in the dtors of a, b, and c when the function returns undefined behavior! We need to redefine copy and assignment into meaningful operations.

61 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 61/69 Copy Constructor template <class T> class Vec { public... Vec(const Vec<T> &rhs);... ; // class Vec<T> Copy ctor is a ctor that takes an object of the same type as the parameter. It is called automatically when there is a need for a copy. The parameter should be of a reference type. Otherwise passing the argument itself would require a copy, which is not defined yet. In most cases, the RHS object shouldn t be changed. Use a const reference for the parameter Use a reference if your class design requires you to do so (very rarely)

62 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 62/69 Implement Copy Constructor Vec(const Vec<T> &rhs) : data_(allocate(rhs.n_)), n_(rhs.n_), capacity_(rhs.n_) { try { uninitialized_copy(rhs.data_, rhs.data_+n, data_); catch (...) { deallocate(data_); throw; Protections are per class instead of per object. So it is possible to access the private members of rhs in the copy ctor.

63 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 63/69 Copy Constructor and Function Calls Vec<int> increment(vec<int> v) { for (size_t i = 0; i < v.size(); ++i) { ++v[i]; return v; void some_function() { Vec<int> zeros(100, 0); Vec<int> ones = increment(zeros); There are 3 places where a copy of the Vec object is made and the copy ctor is called. The argument zeros is copied into the parameter v. The parameter v is copied into the returned result, which is an Vec object w/o a name. The returned result is copied into ones.

64 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 64/69 Assignment Operator template <class T> class Vec { public... Vec<T> &operator=(const Vec<T> &rhs);... ; // class Vec<T> Assignment operator = can be overloaded. It is called automatically for assignment. The parameter could be of any type. We are interested in the RHS object being also a Vec<T> object. So there are 3 choices for the type of the parameter: Vec<T>, const Vec<T> &, Vec<T> &. Using Vec<T> & is rare. Let s start with const Vec<T> &. It s a common practice to require operator= to return the object itself. In order to support assignments like a=b=c=d So the return type must be a reference.

65 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 65/69 Implement Assignment Vec<T> &operator=(const Vec<T> &rhs) { if (this == &rhs) return *this; // nothing to do for self-assignment // prepare new memory/objects value_type *p = allocate(rhs.n_); try { uninitialized_copy(rhs_.data_, rhs_.data_+rhs_.n_, p); catch (...) { deallocate(p); throw; // get rid of old objects/memory for (size_t i = 0; i < n_; ++i) { data_[i].~value_type(); deallocate(data_); // update members data_ = p; n_ = capacity_ = rhs.n_; return *this;

66 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 66/69 Some Ideas on Assignment Roughly speaking, assignment is destruction plus copy construction. Is there a elegant way to call the dtor and the copy ctor in operator= so we don t need to repeat the code?

67 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 67/69 The swap Function template <class T> class Vec { public... void swap(vec<t> &rhs) { std::swap(data_, rhs.data_); std::swap(n_, rhs.n_); std::swap(capacity_, rhs.capacity_);... ; // class Vec<T> It s usually very easy to swap two objects of the same class type: just swap each member. We have seen using references to swap two integers. Actually you can use std::swap for the same purpose. The swap function is so simple that it won t throw.

68 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 68/69 Assignment as Copy-and-Swap Vec<T> &operator=(const Vec<T> &rhs) { if (this == &rhs) return *this; // nothing to do for self-assignment Vec<T> copy = rhs; swap(copy); return *this; We don t need to worry about failures due to exceptions in this function anymore. They are taken care of by ctors and dtor.

69 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 69/69 Summary and Advice Exceptions interact with objects in a complicated way. Stack unwinding: local objects are automatically destroyed even when there is an unhandled exceptions. All or None: either the parent object is constructed successfully or none of the members got constructed. The compiler will synthesize the following special member functions for all types: Default ctor if there is no user-defined ctor. Each of dtor, copy ctor, operator= if it is not defined by user. An synthesized function will propagate the semantics of the function to each data member. The rule of three: if a class owns a kind of resources, e.g. memory on the heap, then dtor, copy ctor, operator= should all be provided for proper resource management. Ctors are always necessary for types with non-trivial class invariants.

ECE 449 OOP and Computer Simulation Lecture 14 Final Exam Review

ECE 449 OOP and Computer Simulation Lecture 14 Final Exam Review ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/35 ECE 449 OOP and Computer Simulation Lecture 14 Final Exam Review Professor Jia Wang Department of Electrical

More information

ECE 449 OOP and Computer Simulation Lecture 12 Resource Management II

ECE 449 OOP and Computer Simulation Lecture 12 Resource Management II ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/62 ECE 449 OOP and Computer Simulation Lecture 12 Resource Management II Professor Jia Wang Department of Electrical

More information

ECE 449 OOP and Computer Simulation Lecture 07 Class Design for Circuit Netlist

ECE 449 OOP and Computer Simulation Lecture 07 Class Design for Circuit Netlist ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/64 ECE 449 OOP and Computer Simulation Lecture 07 Class Design for Circuit Netlist Professor Jia Wang Department

More information

ECE 449 OOP and Computer Simulation Lecture 11 Design Patterns

ECE 449 OOP and Computer Simulation Lecture 11 Design Patterns ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/60 ECE 449 OOP and Computer Simulation Lecture 11 Design Patterns Professor Jia Wang Department of Electrical

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.... COMP6771 Advanced C++ Programming Week 5 Part One: Exception Handling 2016 www.cse.unsw.edu.au/ cs6771 2.... Memory Management & Exception Handling.1 Part I: Exception Handling Exception objects

More information

Exception Safe Coding

Exception Safe Coding Exception Safe Coding Dirk Hutter hutter@compeng.uni-frankfurt.de Prof. Dr. Volker Lindenstruth FIAS Frankfurt Institute for Advanced Studies Goethe-Universität Frankfurt am Main, Germany http://compeng.uni-frankfurt.de

More information

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation Review from Lectures 7 Algorithm Analysis, Formal Definition of Order Notation Simple recursion, Visualization

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

Allocation & Efficiency Generic Containers Notes on Assignment 5

Allocation & Efficiency Generic Containers Notes on Assignment 5 Allocation & Efficiency Generic Containers Notes on Assignment 5 CS 311 Data Structures and Algorithms Lecture Slides Friday, October 30, 2009 Glenn G. Chappell Department of Computer Science University

More information

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington CSE 333 Lecture 11 - constructor insanity Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia Exercises: - New exercise out today, due Monday morning

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions Dan Pomerantz School of Computer Science 19 March 2012 Overloading operators in classes It is useful sometimes to define

More information

Exception Safety. CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, Glenn G. Chappell. continued

Exception Safety. CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, Glenn G. Chappell. continued continued CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005

More information

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms Introduction to Linked Lists Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms Lecture Slides Friday, September 25, 2009 Glenn G. Chappell Department of Computer Science

More information

Contract Programming For C++0x

Contract Programming For C++0x Contract Programming For C++0x WG21/N1800 and J16/05-0060 Lawrence Crowl and Thorsten Ottosen lawrence.crowl@sun.com and nesotto@cs.aau.dk 2005-04-27 Overview This is an annotated version of the presentation

More information

Part X. Advanced C ++

Part X. Advanced C ++ Part X Advanced C ++ topics Philip Blakely (LSC) Advanced C++ 158 / 217 References The following are highly regarded books. They are fairly in-depth, and I haven t read them in their entirity. However,

More information

Basic Array Implementation Exception Safety

Basic Array Implementation Exception Safety Basic Array Implementation Exception Safety CS 311 Data Structures and Algorithms Lecture Slides Monday, October 26, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks

More information

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation Announcements Lab 3 was a Frankenstein assembly of a new group exercise with part of a gdb lab. I hear many of you

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

Lecture Notes on Memory Layout

Lecture Notes on Memory Layout Lecture Notes on Memory Layout 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 11 1 Introduction In order to understand how programs work, we can consider the functions,

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file? QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The

More information

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored

More information

Midterm Review. PIC 10B Spring 2018

Midterm Review. PIC 10B Spring 2018 Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed

More information

6 Architecture of C++ programs

6 Architecture of C++ programs 6 Architecture of C++ programs 1 Preview managing memory and other resources "resource acquisition is initialization" (RAII) using std::auto_ptr and other smart pointers safe construction of an object

More information

CSCI-1200 Data Structures Spring 2013 Lecture 7 Templated Classes & Vector Implementation

CSCI-1200 Data Structures Spring 2013 Lecture 7 Templated Classes & Vector Implementation CSCI-1200 Data Structures Spring 2013 Lecture 7 Templated Classes & Vector Implementation Review from Lectures 5 & 6 Arrays and pointers Different types of memory ( automatic, static, dynamic) Dynamic

More information

Advanced Programming in C++ Container Design I

Advanced Programming in C++ Container Design I Advanced Programming in C++ Container Design I This is an exercise on container design, especially in the view of robustness, iterators, and storage management. The container will be developed step-by-step,

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

04-17 Discussion Notes

04-17 Discussion Notes 04-17 Discussion Notes PIC 10B Spring 2018 1 RAII RAII is an acronym for the idiom Resource Acquisition is Initialization. What is meant by resource acquisition is initialization is that a resource should

More information

use static size for this buffer

use static size for this buffer Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation

More information

CS11 Advanced C++ Fall Lecture 3

CS11 Advanced C++ Fall Lecture 3 CS11 Advanced C++ Fall 2006-2007 Lecture 3 Today s Topics C++ Standard Exceptions Exception Cleanup Fun with Exceptions Exception Specifications C++ Exceptions Exceptions are nice for reporting many errors

More information

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

More information

1 of 8 3/28/2010 8:03 AM C++ Special Topics Home Class Info Links Lectures Newsgroup Assignmen This is a short review of special topics in C++ especially helpful for various assignments. These notes are

More information

Homework 4. Any questions?

Homework 4. Any questions? CSE333 SECTION 8 Homework 4 Any questions? STL Standard Template Library Has many pre-build container classes STL containers store by value, not by reference Should try to use this as much as possible

More information

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370 Part VII Object-Oriented Programming Philip Blakely (LSC) C++ Introduction 194 / 370 OOP Outline 24 Object-Oriented Programming 25 Member functions 26 Constructors 27 Destructors 28 More constructors Philip

More information

CSE 333 Midterm Exam 5/10/13

CSE 333 Midterm Exam 5/10/13 Name There are 5 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes, closed

More information

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary Slide Set 14 for ENCM 339 Fall 2016 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary November 2016 ENCM 339 Fall 2016 Slide Set 14 slide 2/35

More information

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.

More information

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s Session 2 - Classes in C++ Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) A C++ source file may contain: include directives #include

More information

Chapter 13: Copy Control. Overview. Overview. Overview

Chapter 13: Copy Control. Overview. Overview. Overview Chapter 13: Copy Control Overview The Copy Constructor The Assignment Operator The Destructor A Message-Handling Example Managing Pointer Members Each type, whether a built-in or class type, defines the

More information

The C++ Object Lifecycle. EECS 211 Winter 2019

The C++ Object Lifecycle. EECS 211 Winter 2019 The C++ Object Lifecycle EECS 211 Winter 2019 2 Initial code setup $ cd eecs211 $ curl $URL211/lec/09lifecycle.tgz tar zx $ cd 09lifecycle 3 Road map Owned string type concept Faking it An owned string

More information

Vector and Free Store (Pointers and Memory Allocation)

Vector and Free Store (Pointers and Memory Allocation) DM560 Introduction to Programming in C++ Vector and Free Store (Pointers and Memory Allocation) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides

More information

Lecture Notes on Queues

Lecture Notes on Queues Lecture Notes on Queues 15-122: Principles of Imperative Computation Frank Pfenning Lecture 9 September 25, 2012 1 Introduction In this lecture we introduce queues as a data structure and linked lists

More information

Objects Managing a Resource

Objects Managing a Resource Objects Managing a Resource 1 What is a Resource Respects Release/Acquire protocol files (open/close) memory allocation (allocate/free) locks (acquire/release). 2 What is a Resource Objects when constructed,

More information

Assertions and Exceptions

Assertions and Exceptions CS 247: Software Engineering Principles Assertions and Exceptions Reading: Eckel, Vol. 2 Ch. 1 Exception Handling U Waterloo CS247 (Spring 2017) p.1/32 Defensive Programming The question isn t whether

More information

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

class Polynomial { public: Polynomial(const string& N = no name, const vector<int>& C = vector<int>());... }; Default Arguments 1 When declaring a C++ function, you may optionally specify a default value for function parameters by listing initializations for them in the declaration: class Polynomial { public:

More information

Programming in C and C++

Programming in C and C++ Programming in C and C++ 5. C++: Overloading, Namespaces, and Classes Dr. Neel Krishnaswami University of Cambridge (based on notes from and with thanks to Anil Madhavapeddy, Alan Mycroft, Alastair Beresford

More information

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I Polynomial Class Polynomial(); Polynomial(const string& N, const vector& C); Polynomial operator+(const Polynomial& RHS) const; Polynomial operator-(const Polynomial& RHS) const; Polynomial operator*(const

More information

CS11 Advanced C++ Spring 2018 Lecture 2

CS11 Advanced C++ Spring 2018 Lecture 2 CS11 Advanced C++ Spring 2018 Lecture 2 Lab 2: Completing the Vector Last week, got the basic functionality of our Vector template working It is still missing some critical functionality Iterators are

More information

CS93SI Handout 04 Spring 2006 Apr Review Answers

CS93SI Handout 04 Spring 2006 Apr Review Answers CS93SI Handout 04 Spring 2006 Apr 6 2006 Review Answers I promised answers to these questions, so here they are. I'll probably readdress the most important of these over and over again, so it's not terribly

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 11 October 3, 2018 CPSC 427, Lecture 11, October 3, 2018 1/24 Copying and Assignment Custody of Objects Move Semantics CPSC 427, Lecture

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance

More information

QUIZ Friends class Y;

QUIZ Friends class Y; QUIZ Friends class Y; Is a forward declaration neeed here? QUIZ Friends QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They

More information

Lesson 13 - Vectors Dynamic Data Storage

Lesson 13 - Vectors Dynamic Data Storage Lesson 13 - Vectors Dynamic Data Storage Summary In this lesson we introduce the Standard Template Library by demonstrating the use of Vectors to provide dynamic storage of data elements. New Concepts

More information

A Crash Course in (Some of) Modern C++

A Crash Course in (Some of) Modern C++ CMPT 373 Software Development Methods A Crash Course in (Some of) Modern C++ Nick Sumner wsumner@sfu.ca With material from Bjarne Stroustrup & Herb Sutter C++ was complicated/intimidating Pointers Arithmetic

More information

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually

More information

CS102 C++ Exception Handling & Namespaces

CS102 C++ Exception Handling & Namespaces CS102 C++ Exception Handling & Namespaces Bill Cheng http://merlot.usc.edu/cs102-s12 1 Topics to cover C Structs (Ch 10) C++ Classes (Ch 11) Constructors Destructors Member functions Exception Handling

More information

Templates and Vectors

Templates and Vectors Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions

More information

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,

More information

Object Oriented Software Design - II

Object Oriented Software Design - II Object Oriented Software Design - II Safety to exceptions Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa April 12, 2012 G. Lipari (Scuola Superiore Sant Anna) Exception Safety

More information

Lecture 10 Notes Linked Lists

Lecture 10 Notes Linked Lists Lecture 10 Notes Linked Lists 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, Rob Simmons, André Platzer 1 Introduction In this lecture we discuss the use of linked lists to

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 4 Date:

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Reading for this lecture: Carrano, Chapter 2 Copy constructor, destructor, operator=

More information

Engineering Robust Server Software

Engineering Robust Server Software Engineering Robust Server Software Exceptions Exceptions Handling problems: exceptions C++ Java temp-and-swap RAII Smart Pointers finally specifications finalizers (and why they are not what you need for

More information

CSE 333 Midterm Exam Sample Solution 5/10/13

CSE 333 Midterm Exam Sample Solution 5/10/13 Question 1. (18 points) Consider these two C files: a.c void f(int p); int main() { f(17); return 0; b.c void f(char *p) { *p = 'x'; (a) Why is the program made from a.c and b.c incorrect? What would you

More information

04-19 Discussion Notes

04-19 Discussion Notes 04-19 Discussion Notes PIC 10B Spring 2018 1 Constructors and Destructors 1.1 Copy Constructor The copy constructor should copy data. However, it s not this simple, and we need to make a distinction here

More information

PHY4321 Summary Notes

PHY4321 Summary Notes PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t

More information

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011 More C++ David Chisnall March 17, 2011 Exceptions A more fashionable goto Provides a second way of sending an error condition up the stack until it can be handled Lets intervening stack frames ignore errors

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 4 Part One: (continued) and 2016 www.cse.unsw.edu.au/ cs6771 2. Inline Constructors, Accessors and Mutators Question (from 2015): In the week 3 examples, constructors

More information

AIMS Embedded Systems Programming MT 2017

AIMS Embedded Systems Programming MT 2017 AIMS Embedded Systems Programming MT 2017 Object-Oriented Programming with C++ Daniel Kroening University of Oxford, Computer Science Department Version 1.0, 2014 Outline Classes and Objects Constructors

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer October 10, 2016 OOPP / C++ Lecture 7... 1/15 Construction and Destruction Kinds of Constructors Move Semantics OOPP / C++ Lecture 7... 2/15

More information

Intermediate Programming & Design (C++) Classes in C++

Intermediate Programming & Design (C++) Classes in C++ Classes in C++ A class is a data type similar to a C structure. It includes various local data (called data members) together with constructors, destructors and member functions. All of them are called

More information

G52CPP C++ Programming Lecture 16

G52CPP C++ Programming Lecture 16 G52CPP C++ Programming Lecture 16 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Casting static cast dynamic cast const cast reinterpret cast Implicit type conversion 2 How

More information

ECE 449 OOP and Computer Simulation Lecture 09 Logic Simulation

ECE 449 OOP and Computer Simulation Lecture 09 Logic Simulation ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/31 ECE 449 OOP and Computer Simulation Lecture 09 Logic Simulation Professor Jia Wang Department of Electrical

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Error Handling and Exceptions Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer

More information

Lecture 10 Notes Linked Lists

Lecture 10 Notes Linked Lists Lecture 10 Notes Linked Lists 15-122: Principles of Imperative Computation (Summer 1 2015) Frank Pfenning, Rob Simmons, André Platzer 1 Introduction In this lecture we discuss the use of linked lists to

More information

Chapter 17 vector and Free Store

Chapter 17 vector and Free Store Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:

More information

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

double d0, d1, d2, d3; double * dp = new double[4]; double da[4]; All multiple choice questions are equally weighted. You can generally assume that code shown in the questions is intended to be syntactically correct, unless something in the question or one of the answers

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Reminder: compiling & linking

Reminder: compiling & linking Reminder: compiling & linking source file 1 object file 1 source file 2 compilation object file 2 library object file 1 linking (relocation + linking) load file source file N object file N library object

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

Motivation was to facilitate development of systems software, especially OS development.

Motivation was to facilitate development of systems software, especially OS development. A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.

More information

Modern and Lucid C++ Advanced for Professional Programmers. Part 3 Move Semantics. Department I - C Plus Plus Advanced

Modern and Lucid C++ Advanced for Professional Programmers. Part 3 Move Semantics. Department I - C Plus Plus Advanced Department I - C Plus Plus Advanced Modern and Lucid C++ Advanced for Professional Programmers Part 3 Move Semantics Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 09.03.2018 HS2018 Move Semantics 2

More information

18. Dynamic Data Structures I. Dynamic Memory, Addresses and Pointers, Const-Pointer Arrays, Array-based Vectors

18. Dynamic Data Structures I. Dynamic Memory, Addresses and Pointers, Const-Pointer Arrays, Array-based Vectors 590 18. Dynamic Data Structures I Dynamic Memory, Addresses and Pointers, Const-Pointer Arrays, Array-based Vectors Recap: vector 591 Can be initialised with arbitrary size n 591 Recap: vector

More information

Written by John Bell for CS 342, Spring 2018

Written by John Bell for CS 342, Spring 2018 Advanced OO Concepts Written by John Bell for CS 342, Spring 2018 Based on chapter 3 of The Object-Oriented Thought Process by Matt Weisfeld, with additional material from other sources. Constructors Constructors

More information

05-01 Discussion Notes

05-01 Discussion Notes 05-01 Discussion Notes PIC 10B Spring 2018 1 Exceptions 1.1 Introduction Exceptions are used to signify that a function is being used incorrectly. Once an exception is thrown, it is up to the programmer

More information

Chapter 17 vector and Free Store

Chapter 17 vector and Free Store Chapter 17 vector and Free Store Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~hkaiser/fall_2010/csc1253.html Slides adapted from: Bjarne Stroustrup, Programming Principles and Practice using

More information

Splicing Maps and Sets (Revision 1)

Splicing Maps and Sets (Revision 1) Document number: N3645 Date: 2013-05-04 Project: Programming Language C++ Reference: N3485 Reply to: Alan Talbot cpp@alantalbot.com Howard Hinnant howard.hinnant@gmail.com James Dennett jdennett@google.com

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 12 October 10, 2016 CPSC 427, Lecture 12 1/27 Uses of Pointers Custody of Objects Move Semantics CPSC 427, Lecture 12 2/27 Uses of Pointers

More information

377 Student Guide to C++

377 Student Guide to C++ 377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided

More information

C++ Primer for CS175

C++ Primer for CS175 C++ Primer for CS175 Yuanchen Zhu September 10, 2014 This primer is pretty long and might scare you. Don t worry! To do the assignments you don t need to understand every point made here. However this

More information