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

Similar documents
G52CPP C++ Programming Lecture 16

Exception Safe Coding

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers

Midterm Review. PIC 10B Spring 2018

6 Architecture of C++ programs

Homework 4. Any questions?

Pointers. Developed By Ms. K.M.Sanghavi

Laboratorio di Tecnologie dell'informazione

What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.

CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers

Smart Pointers. Some slides from Internet

IS 0020 Program Design and Software Tools

377 Student Guide to C++

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

Exceptions and Design

C++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

CA341 - Comparative Programming Languages

COMP6771 Advanced C++ Programming

CS11 Advanced C++ Fall Lecture 3

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

Design Patterns in C++

CSE 333 Lecture smart pointers

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Assertions and Exceptions

Exception Handling Pearson Education, Inc. All rights reserved.

C++ Primer for CS175

CS11 Introduction to C++ Fall Lecture 6

COMP 2355 Introduction to Systems Programming

Doc. No.: WG21/N0937=X3J16/ Date: 28 May 1996 Project: C++ Standard Library Reply to: Nathan Myers

Short Notes of CS201

Kakadu and Java. David Taubman, UNSW June 3, 2003

Classes, Constructors, etc., in C++

C++_ MARKS 40 MIN

C++ Programming Lecture 7 Software Engineering Group

G52CPP C++ Programming Lecture 20

CS201 - Introduction to Programming Glossary By

Security impact of noexcept

G52CPP C++ Programming Lecture 9

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

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

Interview Questions of C++

CS 241 Honors Memory

Today s Big Adventure

! Errors can be dealt with at place error occurs

Today s Big Adventure

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

COMP6771 Advanced C++ Programming

Object Oriented Software Design - II

CPSC 427: Object-Oriented Programming

GEA 2017, Week 4. February 21, 2017

CPSC 427: Object-Oriented Programming

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

A Whirlwind Tour of C++

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

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

04-19 Discussion Notes

CSE 333 Lecture smart pointers

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

TEMPLATES AND EXCEPTION HANDLING

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

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

6. Pointers, Structs, and Arrays. 1. Juli 2011

Allocation & Efficiency Generic Containers Notes on Assignment 5

And Even More and More C++ Fundamentals of Computer Science

CPSC 427: Object-Oriented Programming

Ch. 10: Name Control

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

Objects Managing a Resource

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

QUIZ Friends class Y;

MODERN AND LUCID C++ ADVANCED

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

CS 11 C track: lecture 5

Memory Management: The Details

Intermediate Programming, Spring 2017*

CGS 2405 Advanced Programming with C++ Course Justification

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

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

CS3157: Advanced Programming. Outline

Memory and C/C++ modules

QUIZ. Source:

ALL ABOUT POINTERS C/C++ POINTERS

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

Copyie Elesion from the C++11 mass. 9 Sep 2016 Pete Williamson

C++: Overview and Features

Agenda. CSE P 501 Compilers. Java Implementation Overview. JVM Architecture. JVM Runtime Data Areas (1) JVM Data Types. CSE P 501 Su04 T-1

Reminder: compiling & linking

CSE 333 Lecture smart pointers

Stream Computing using Brook+

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

AIMS Embedded Systems Programming MT 2017

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

III. Classes (Chap. 3)

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems

Exercise 6.2 A generic container class

Instantiation of Template class

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

Part III. Advanced C ++

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2015 Lecture 11

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Transcription:

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 Comes from languages with garbage collection Huge problem with languages that don t have it! (like C/C++)

The Basic Idea // Throw an exception throw x; try somethingthatmaythrowanexception (); } catch ( int a) // Exceptions don t have to be objects } catch (...) cleanup (); throw ; }

Differences from Java Can throw anything that supports copying, not just objects No finally statement. Can be emulated with catchall and rethrow

How it Works: The Old Way Every try block pushes a handler function and the current instruction and stack pointer onto the exception stack Exiting the try block pops the handler Exceptions run by calling the handler then setting the instruction and stack pointers.

Why It Doesn t (Usually) Work That Way Now Exceptions are meant to be unusual This imposed a cost for every try block Even when no exception is thrown.

Zero Cost Exceptions Each stack frame contains some metadata saying where the exception handlers are Often in the same format as debug info Throw function visits walks the stack reading this metadata Reconfigures stack for each handler

Exception Performance Zero-cost exceptions cost nothing when entering a try block Throwing an exception is very slow Can be hundreds of times more expensive than a function call

Exception Specifiers // May only throw a std :: bad_ alloc exception int foo ( void ) throw ( std :: bad_alloc ); // May not throw any exceptions int bar ( void ) throw (); Exception specifiers are enforced at run time Violation invokes a callback function Typically aborts the program Could just abort the thread

Exceptions and Memory Management // Class on the stack, destructor will be called SomeClass f; // Simple stack allocation, no cleanup needed int b; // Pointer. Just leaks! SomeClass * f = new SomeClass (); // Exception thrown, maybe from some called function throw a;

Namespaces Non-virtual methods in C++ are really just functions that are in a restricted namespace C++ generalises this, allowing all declarations to be inside namespaces Namespaces can be imported into the current context, or have elements from them used directly All of this works via the name mangling mechanism

Namespace Examples namespace a namespace b void function ( void ); } void function ( void ); }; // Note the semicolon! // Calling a::b:: function (); a:: function (); using namespace a; function (); using a::b:: function ; function ();

Namespaces in Use Anonymous namespace declarations not exported Standard C headers come in namespaced versions #include <stdio.h> is the same as C #include <stdio> gives the same functions in the std:: namespace // Put all functions from some C lib into a namespace namespace somelib # include < somelib.h> };

Interoperability With C C doesn t support name mangling C doesn t support classes C usually defines the interoperable ABI for a platform - other languages can call C, but often not C++

Turn Off Name Mangling extern "C" // Header that isn t designed for use by C ++ # include < some_c_header.h> } // Turn off name mangling for this function extern " C" int fortytwo ( void ) throw () return 42; } extern "C" specifies C linkage Used when declaring a C function, or exporting a function for use by C code Disables overloading and namespaces for that function Functions exported to C should usually not throw exceptions!

C/C++ Headers # ifdef cplusplus extern "C" # define NOTHROW throw () # else # ifdef GNUC # define NOTHROW attribute (( nothrow )) # else # define NOTHROW # endif # endif void somefunction ( void ) NOTHROW ; # ifdef cplusplus } # endif

Templates Metaprogramming For C++ C++ templates are written in the C++ template language C++ code with some placeholders Placeholders filled in when template is used A big part of the reason C++ executables are so huge

Templates for Type-Generic Use template < typename T> T max (T a, T b) return a>b? a : b; } int a = max (1,2) ; std :: vector <int > vector ; Template parameter defines the type Instantiated with the type where used Used for all of the STL collections

Templates for Exception-Safe Pointers std :: auto_ptr < SomeClass > p( new SomeClass ()); p is an on-stack instance of std::auto_ptr The std::auto_ptr class wraps the pointer Assigning the pointer removes ownership from the auto_ptr The auto_ptr s destructor deletes the object Exception-safe cleanup of pointers

Smart Pointers Template, wraps a pointer Copy constructor increments reference count Destructor decrements reference count Object freed when last smart pointer destroyed Very hard to get right Provided by Boost, C++0X

Templates for Compile-Time Calculation template < unsigned int n > struct fib static const unsigned int result = fib <n -1 >:: result +fib <n -2 >:: result ; }; template < > struct fib <1 > static const unsigned int result =1; }; template < > struct fib <0 > static const unsigned int result =0; }; int main ( void ) printf ("%d\n", fib <9 >:: result ); }

Template Performance Instantiated at compile time Not instantiated multiple times Template recursive Fibonacci is O(n) Nontrivial templates take a lot of time to compile Linker will try to remove identical template instantiations Sometimes, it fails (e.g. std::vector<uintptr_t> and std::vector<void*>)

Questions?