CPSC 427: Object-Oriented Programming

Similar documents
CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

Midterm Review. PIC 10B Spring 2018

COMP6771 Advanced C++ Programming

G52CPP C++ Programming Lecture 16

05-01 Discussion Notes

COMP6771 Advanced C++ Programming

CPSC 427: Object-Oriented Programming

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

IS 0020 Program Design and Software Tools

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming

Exception Handling Pearson Education, Inc. All rights reserved.

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Laboratorio di Tecnologie dell'informazione

COMP 2355 Introduction to Systems Programming

Homework 4. Any questions?

CPSC 427: Object-Oriented Programming

! Errors can be dealt with at place error occurs

TEMPLATES AND EXCEPTION HANDLING

Assertions and Exceptions

Study Guide to Exam 2

CPSC 427: Object-Oriented Programming

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

04-24/26 Discussion Notes

CPSC 427a: Object-Oriented Programming

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Ch. 12: Operator Overloading

Short Notes of CS201

Object Oriented Programming

CSCE 110 PROGRAMMING FUNDAMENTALS

CS201 - Introduction to Programming Glossary By

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

Error Handling in C++

ALL ABOUT POINTERS C/C++ POINTERS

17.1 Handling Errors in a Program

CPSC 427: Object-Oriented Programming

Preconditions. CMSC 330: Organization of Programming Languages. Signaling Errors. Dealing with Errors

Absolute C++ Walter Savitch

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Object-Oriented Programming for Scientific Computing

Programming in C++: Assignment Week 8

CA341 - Comparative Programming Languages

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Inheritance, and Polymorphism.

Exception handling. Aishy Amer. Lecture Outline: Introduction Types or errors or exceptions Conventional error processing Exception handling in C++

CSC 211 Intermediate Programming. Arrays & Pointers

COE318 Lecture Notes Week 10 (Nov 7, 2011)

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Intermediate Programming, Spring 2017*

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Advanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const.


Introduction. Common examples of exceptions

AN OVERVIEW OF C++ 1

Contents. Error Handling Strategies (cont d) Error handling strategies: error code, assert(), throw-try-catch

CS 485 Advanced Object Oriented Design. Enum. Spring 2017

A brief introduction to C++

04-19 Discussion Notes

Introduction Of Classes ( OOPS )

CS11 Advanced C++ Fall Lecture 3

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

Object Oriented Programming

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

CPSC 427: Object-Oriented Programming

VALLIAMMAI ENGINEERING COLLEGE

Classes, The Rest of the Story

LECTURE 03 LINKED LIST

CPSC 427a: Object-Oriented Programming

Exceptions, Case Study-Exception handling in C++.

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

C++ For Science and Engineering Lecture 15

G52CPP C++ Programming Lecture 20

void fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) {

Polymorphism Part 1 1

CPSC 427: Object-Oriented Programming

Pointers. Developed By Ms. K.M.Sanghavi

Exception with arguments

Lecture 2. CS118 Term planner. Refinement. Recall our first Java program. Program skeleton GCD. For your first seminar. For your second seminar

Problem Solving with C++

Introducing C++ to Java Programmers

Object Oriented Programming: Inheritance Polymorphism

C10: Garbage Collection and Constructors

C++ Programming Lecture 7 Software Engineering Group

Smart Pointers. Some slides from Internet

CPSC 427: Object-Oriented Programming

Programming in C++: Assignment Week 8

Cpt S 122 Data Structures. Introduction to C++ Part II

1. Which of the following best describes the situation after Line 1 has been executed?

COMP1008 Exceptions. Runtime Error

Pointers and References

04-17 Discussion Notes

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

2 ADT Programming User-defined abstract data types

Financial computing with C++

Transcription:

CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 20 November 12, 2018 CPSC 427, Lecture 20, November 12, 2018 1/26

Rethrowing Exceptions Uncaught Exceptions Singleton Design Pattern Smart Pointer Demo CPSC 427, Lecture 20, November 12, 2018 2/26

Rethrowing Exceptions CPSC 427, Lecture 20, November 12, 2018 3/26

Rethrow A catch block can do some processing and then optionally rethrow the exception or throw a new exception. One exception can cause multiple catch blocks to execute. To rethrow the same exception, use throw; with no argument. To throw a new exception, use throw as usual with an argument. CPSC 427, Lecture 20, November 12, 2018 4/26

A subtle fact about rethrow Rethrowing the current exception is not the same as throwing an exception with the same exception object. throw e; always copies object e to special memory using the copy constructor for e s class. throw; does not make another copy of the exception object but instead uses the copy already in special memory. This difference becomes apparent if the copy is not identical to the original (possible for a custom copy constructor), or if the copy constructor has side effects (such as printing output). CPSC 427, Lecture 20, November 12, 2018 5/26

Example of rethrowing an exception (demo 20a-Exceptions-rethrow) 1 #include <iostream> 2 using namespace std; 3 class MyException { 4 public: 5 MyException() {} 6 MyException( MyException& e ) { 7 cout << "Copy constructor called\n"; } 8 ~MyException() {} 9 } myex; // declares class and instantiates it 10 int main () { 11 try { 12 try { throw myex; } 13 catch (MyException& e) { 14 cout << "Exception caught by inner catch\n"; throw; } 15 } 16 catch (MyException& err) { 17 cout << "Exception caught by outer catch\n"; 18 } 19 return 0; 20 } CPSC 427, Lecture 20, November 12, 2018 6/26

Results In the preceding example, the throw myex on line 12 causes a copy, but the throw on line 14 does not. This produces the following output: Copy constructor called Exception caught by inner catch Exception caught by outer catch CPSC 427, Lecture 20, November 12, 2018 7/26

Uncaught Exceptions CPSC 427, Lecture 20, November 12, 2018 8/26

Uncaught exceptions: Ariane 5 Uncaught exceptions have led to spectacular disasters. The European Space Agency s Ariane 5 Flight 501 was destroyed 40 seconds after takeoff (June 4, 1996). The US$1 billion prototype rocket self-destructed due to a bug in the on-board guidance software. [Wikipedia] This is not about a programming error. It is about system-engineering and design failures. The software did what it was designed to do and what it was agreed that it should do. CPSC 427, Lecture 20, November 12, 2018 9/26

Uncaught exceptions: Ariane 5 (cont.) Heres a summary of the events and its import for system engineering: A decision was made to leave a program running after launch, even though its results were not needed after launch. An overflow error happened in that calculation, An exception was thrown and, by design, was not caught. This caused the vehicle s active and backup inertial reference systems to shut down automatically. As the result of the unanticipated failure mode and a diagnostic message erroneously treated as data, the guidance system ordered violent attitude correction. The ensuing disintegration of the over-stressed vehicle triggered the pyrotechnic destruction of the launcher and its payload. CPSC 427, Lecture 20, November 12, 2018 10/26

Termination There are various conditions under which the exception-handling mechanism can fail. Two such examples are: Exception not caught by any catch block. A destructor issues a throw during the stack-unwinding process. When this happens, the function terminate() is called, which by default aborts the process. 1 This is a bad thing in production code. Conclusion: All exceptions should be caught and dealt with explicitly. 1 It s behavior can be changed by the user. CPSC 427, Lecture 20, November 12, 2018 11/26

Singleton Design Pattern CPSC 427, Lecture 20, November 12, 2018 12/26

Unique IDs Unique identifiers (UIDs) are familiar in many situations: Appliance serial numbers, automobile VINs, social security numbers, and so forth. They are useful in programming as well. Whenever a class has many instances, UIDs can help track objects from the time they are created until their eventual deletion. This is especially helpful when custody changes during the lifetime of the object. UIDs are very helpful in identifying error comments during debugging. They are also helpful when included in log files. CPSC 427, Lecture 20, November 12, 2018 13/26

How to generate UIDs A method for adding UIDs to class instances involves the following steps: 1. Add a data member const unsigned uid to the class. 2. Add a static variable unsigned nextuid to the class. 3. Initialize nextuid to 0. 4. In every constructor, initialize uid to nextuid++. Recall that static variables cannot be initialized within the class but rather in a.cpp file. CPSC 427, Lecture 20, November 12, 2018 14/26

Drawbacks to the simple method Drawbacks to the simple approach: It adds clutter to the class. It violates OO principles by mixing together the UID generation process with whatever else the class is doing. It results in code replication if UIDs are being used in more than one class. CPSC 427, Lecture 20, November 12, 2018 15/26

A UID generator What we want is a class Serial with a private data member nextuid and a public function uidgen() that returns and updates the next UID. In order to call the function, we need a class instance uidgen of Serial that initializes nextuid and supports the public function uidgen(). Now, to generate a new serial number, simply call uidgen.uidgen(). However, this solution has two problems: 1. How can one make the object uidgen available wherever needed? 2. Where should Serial be instantiated? CPSC 427, Lecture 20, November 12, 2018 16/26

Singleton class A singleton class solves both problems. 1. It has a static function that returns a pointer to the single instantiation whenever it is called. 2. Initially there is no instantiation, so it creates and remembers an instantation the first time it is called. It uses a private static variable for this purpose. CPSC 427, Lecture 20, November 12, 2018 17/26

Functors A functor is an object that acts like a function. Let obj be a functor. Then one can write obj(), pretending that obj is a function. All that is needed to make this work is to define operator() within the class. For our UID generator, we define the behavior of obj to be the same as for uidgen() discussed above. CPSC 427, Lecture 20, November 12, 2018 18/26

Serial.hpp // Singleton class for generating unique ID s class Serial { private: static Serial* Sobj; int nextuid=0; Serial() =default; public: static Serial& uidgen() { if (Sobj == nullptr) Sobj = new Serial; return *Sobj; } const int operator()() { return nextuid++; } }; CPSC 427, Lecture 20, November 12, 2018 19/26

Serial.cpp // Initialize Serializer static variable Serial* Serial::Sobj = nullptr; CPSC 427, Lecture 20, November 12, 2018 20/26

Smart Pointer Demo CPSC 427, Lecture 20, November 12, 2018 21/26

Dangling pointers Pointers can be used to permit object sharing from different contexts. One can have a single object of some type T with many pointers in different contexts that all point to that object. CPSC 427, Lecture 20, November 12, 2018 22/26

Problems with shared objects If the different contexts have different lifetimes, the problem is to know when it is safe to delete the object. It can be difficult to know when an object should be deleted. Failure to delete an object will cause memory leaks. If the object is deleted while there are still points pointing to it, then those pointers become invalid. We call these dangling pointers. Failure to delete or premature deletion of objects are common sources of errors in C++. CPSC 427, Lecture 20, November 12, 2018 23/26

Avoiding dangling pointers There are several ways to avoid dangling pointers. 1. Have a top-level manager whose lifetime exceeds that of all of the pointers take responsibility for deleting the objects. 2. Use a garbage collection. (This is java s approach.) 3. Use reference counts. That is, keep track somehow of the number of outstanding pointers to an object. When the last pointer is deleted, then the object is deleted at that time. CPSC 427, Lecture 20, November 12, 2018 24/26

Modern C++ Smart Pointers Modern C++ has three kinds of smart pointers. These are objects that act very much like raw pointers, but they take responsibility for managing the objects they point at and deleting them when appropriate. shared ptr weak ptr unique ptr We will discuss them later in the course, time permitting. For now, we present a simplified version of shared pointer so that you can see the basic mechanism that underlies all of the various kinds of shared pointers. CPSC 427, Lecture 20, November 12, 2018 25/26

Smart pointers We define a class SPtr of reference-counted pointer-like objects. An SPtr should act like a pointer to a T. This means if sp is an SPtr, then *sp is a T&. We need a way to create a smart pointer and to create copies of them. Demo 20b-SmartPointer illustrates how this can be done. CPSC 427, Lecture 20, November 12, 2018 26/26