Objects Managing a Resource

Similar documents
Homework 4. Any questions?

2 ADT Programming User-defined abstract data types

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

StackVsHeap SPL/2010 SPL/20

Smart Pointers. Some slides from Internet

CPSC 427: Object-Oriented Programming

An Introduction to C++

Short Notes of CS201

COMP6771 Advanced C++ Programming

CS201 - Introduction to Programming Glossary By

CPSC 427: Object-Oriented Programming

CS11 Advanced C++ Spring 2018 Lecture 2

COMP6771 Advanced C++ Programming

Object-Oriented Principles and Practice / C++

Synchronization SPL/2010 SPL/20 1

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

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

C10: Garbage Collection and Constructors

COMP 2355 Introduction to Systems Programming

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Object Oriented Design

C11: Garbage Collection and Constructors

Interview Questions of C++

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

Lecture 15a Persistent Memory & Shared Pointers

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

ADT: Design & Implementation

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

Object-Oriented Programming for Scientific Computing

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

use static size for this buffer

CPSC 427: Object-Oriented Programming

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

G Programming Languages - Fall 2012

SERIOUS ABOUT SOFTWARE. Qt Core features. Timo Strömmer, May 26,

Part X. Advanced C ++

explicit class and default definitions revision of SC22/WG21/N1582 =

Study Guide to Exam 2

Object-Oriented Programming for Scientific Computing

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

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

Advanced Systems Programming

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

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

Object-Oriented Principles and Practice / C++

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

Question Paper Code : 97044

Introducing C++ to Java Programmers

Allocation & Efficiency Generic Containers Notes on Assignment 5

CMSC 132: Object-Oriented Programming II

G Programming Languages - Fall 2012

CSE 307: Principles of Programming Languages

In Java we have the keyword null, which is the value of an uninitialized reference type

CMSC 132: Object-Oriented Programming II

Vector and Free Store (Pointers and Memory Allocation)

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

Introduction to Programming Using Java (98-388)

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Object-Oriented Principles and Practice / C++

Object Oriented Software Design II

Written by John Bell for CS 342, Spring 2018

6 Architecture of C++ programs

Pointers and Terminal Control

Object Oriented Paradigm

Consider the program...

CSE 333 Lecture smart pointers

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

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

CSC1322 Object-Oriented Programming Concepts

CS201 Some Important Definitions

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

CSE 333 Lecture smart pointers

Chapter 17 vector and Free Store

Aggregation. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

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

ECE 449 OOP and Computer Simulation Lecture 12 Resource Management II

Vector and Free Store (Vectors and Arrays)

Chapter 17 vector and Free Store

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Object-Oriented Programming

CA31-1K DIS. Pointers. TA: You Lu

Lecture 5. Function Pointers

Class object initialization block destructor Class object

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

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

1 Shyam sir JAVA Notes

OBJECT ORIENTED DATA STRUCTURE & ALGORITHMS

Inheritance STL. Entity Component Systems. Scene Graphs. Event Systems

Contract Programming For C++0x

CS201- Introduction to Programming Current Quizzes

Part III. Advanced C ++

CS3157: Advanced Programming. Outline

COEN244: Class & function templates

Programming in C and C++

Assignment of Structs

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Chapter 13: Copy Control. Overview. Overview. Overview

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Transcription:

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, sometime acquire a resource. If designed carefully - acquire resource otherwise (when unavone oidable) will acquire several resources When an object is destructed, its resources must be released. 3

Construction of objects 1. Allocating - Allocating enough memory to hold the object's state 2. Initialization - Initializing the internal state of the object. This involves 2 sub-steps: 1. Acquiring Resources - Acquiring the necessary resources which the object requires 2. Consistent state - Making sure that the initial state of the object is valid according to the class invariants 4

Construction of objects RTE allocates the needed memory and calls the constructor of the class. constructor is different from normal method invocation object does not exist until the construction is finished. do not access this of object in the constructor. do not throw exceptions from the constructor 5

destruction of the object when an object is constructed, resources are allocated: explicitly, by the object's constructor implicitly memory allocated to hold the object's state resources should be deallocated. programmer's responsibility of releasing the resources acquired by a process 6

destruction of the object Releasing resources - releasing all of the resources acquired by the object during the object's lifetime and construction. Releasing memory - releasing all the memory allocated for the object 7

Who destructs what? destructing an object is shared between the RTE and the programmer: programmer releases resources acquired by constructor or during the life time RTE is responsible to release the memory allocated to hold the state of the object. 8

How to destruct? object is implicitly destructed if object is allocated on stack. when the program exits the scope of this object, the RTE will destruct the object. object allocated on the heap is destructed explicitly, by the programmer use delete operator on a pointer to the object. 9

Destruction order RTE calls a special function of the objectdestructor. responsibility of the programmer to implement such a function, and release all resources acquired by the object during the object's lifetime. RTE releases memory used to hold the object's state from stack or heap 10

LifeCycle of an Object object is "born" after constructor successfully terminates. object "retired" after destructor successfully terminates. object is "alive following its construction and just before its destruction. object is valid only as long as the object is alive. 11

Shape Collection Example object that holds a collection of shapes. will not create new shapes on its own will receive previously constructed shapes to store build the class 12

13

C++ interface Shape is an interface as all its functions are pure virtual [=0] in declaration Pure virtual are functions that the compiler enforce us to implement. An interface in C++ is implemented by using regular inheritance (C++ multiple inheritance) /**... */ - special tokens recognized by doxygen for auto documentation 14

15

16

Remarks class Shape - is a forward declaration typedef is used to define new types Shapes is a type (just like int or any other class). common to replace long types to short std::vector<t> is a C++ template that holds a collection of type T. 17

Remarks add() is receiving const Shape* - Shapes is of type vector<shape*> => Shapes vector cannot directly hold pointers received by add function (parameter is const and vector is not const) shapes are cloned and stored in collection cant just be referenced by the collection. fits well with collection description 18

Implementation 19

Remarks assert(shape!= 0) - as Add receives a pointer it must check for nullity. check man assert shapes_.size() must be const 20

Memory leak class hold clones of Shapes - responsible for releasing clones upon object destruction. add appropriate dtor to ShapeCollection 21

22

Remarks iterator is a pointer to an item of type T (here Shape*). Dereferencing iterator returns Shape* Dereferencing again to access a public method/member (**T) 23

Remarks Destructors are declared virtual inheritance If no good reason - declare each method as virtual. *i=0 for educational reasons. 24

Memory Addresses Aliasing 25

What is the problem? shapes passed to byval is copied to s. no copy-ctor implementation default copy constructor performs a shallow copy of the object's state. shapes_ vector of shapes is copied. shapes on the heap pointed twice: from shapes, and from s!!! 26

What is the problem? byval returns - destructor is called all the shapes of s are freed. shapes holds pointers to shape addresses in heap 27

Assignment (=) problem same problem arises with the assignment operator every Class is a type - supports assignment. given two ShapeCollections, s1 and s2: s1=s2 (s1=s1) exactly as you would do for int or double 28

Solution: copy define copy / assignment behavior possible behaviors are: 1. Do not allow one or both of them 2. Explicitly implement behavior which is consistent with the class design 29

empty behavior should be implemented with every class you write. if later you need copy or assignment - move to second solution. How? declare copy constructor and assignment operator as private! 30

copy-ctor called upon object construction syntax: given a const reference to another object of the same type (which you would not want to change) copy its state to this object state 31

Class(const Class& other) = ctor - copy behavior 32

Class(const Class& other) = ctor - copy behavior 33

Shapes::const_iterator an iterator to a const member of the Shapes vector. 34

assignment: operator= special method of the object syntax: given another object of the same type (which you would not want to change) copy its state to this object's state return an L-Value - meaning return the value of the left object. make sure an object is not assigned to itself 35

36

need to define such behaviors on classes someone will extend class in the future. inheritance techniques to reduce the overhead. 37

Managing Heap resource on Stack Recall: compiler calls ctor, dtor of objects declared on the stack automatically - when the scope is entered and exited when object is copied, the compiler calls the copy constructor. same for assignment (=) 38

Memory management class follow semantics of objects on the stack create generic class to hold object's pointer upon copy or assignment will not really copy the pointer but share it. count how many times the object is being referenced not delete it (when dtor is called) until the last reference is gone. 39

shared_ptr Boost - extension to the standard template library (STL), offering many advanced utilities use a shared_ptr when you have multiple pointers to the same pointee 40

41

On stack! 42

Remarks much shorter and cleaner. wrap the object of interest (shape*) - define a shared_ptr object on stack shared_ptr can then safely be given by value what we need, rather than the copy behavior 43

How does shared_ptr works? NO! copy or assignment behavior: Default: copy by val of all object's state. collection's state is shapes_ of type vector<shared_ptr<shape>> copy-ctor of vector is called vector holds a collection of objects - shared_ptr<shape> (shshape) 44

How does shared_ptr works? vector's copy-ctor copy by value shared_ptr copy-ctor shares pointer to actual shape on the heap shared_ptr holds a pointer and manages the reference count of this pointer shared_ptr copy-ctor and =operator - copy pointer by value manage the reference counting, with destructor 45

How does shared_ptr works? shared_ptr<t>t1 assigned to shared_ptr<t>t2 the pointer managed by t1 is copied to t2, such that they now manage the same pointer. t1 and t2 share a counter to count how many shared_ptr s are managing the same pointer. copying the pointer and sharing the counter t2 increments the reference counter by one. 46

How does shared_ptr works? t1=t2 If t2 had a pointer prior to copy, this pointer's reference count is first decreased by one. 47

How does shared_ptr works? When the dtor of shared_ptr is called - reference count is decreased. If count reaches zero, pointer managed by shared_ptr is deleted. 48

Exceptions During Construction problem may arise during ctor - lead to an exception being thrown exception during construction - object in an undetermined state. Re-implementing the new operator. master C++ 49

Exceptions During Construction Catching exceptions in ctor itself. two major problems: 1. construction needs to fail - no way of signaling this other than exception 2. can not handle out of memory exception inside ctor - thrown before ctor (by new) 50

Exceptions During Construction use the Factory design pattern; static method - in charge of initializing new objects return a pointer to a newly initialized object upon success or a null otherwise. 51

Factory Method any method whose main purpose is creation of objects. used to allow performing dangerous operation while creating an object example: memory allocation, accessing files, publishing the object address Factory Methods in Java for immutable objects. use of factory method has a wider scope 52

53

54

Arrays and Objects how to allocate arrays of primitive types in C++ each cell of the array is initialized using the default constructor. holds also for objects. 55

Each cell of the array is initialized twice! 1. the array is constructed, by using default ctor 2. using the assignment operator. total of 84! Shape objects created on stack 56

STL - containers Sequence containers: vectorvector (class template) dequedouble ended queue (class template) listlist (class template) Container adaptors: stacklifo stack (class template) queuefifo queue (class template) priority_queuepriority queue (class template) Associative containers: setset (class template) multisetmultiple-key set (class template) mapmap (class template) multimapmultiple-key map (class template) bitsetbitset (class template) 57

Sort void sort ( RandomAccessIterator first, RandomAccessIterator last ); void sort ( RandomAccessIterator first, RandomAccessIterator last, bool compare ); 58

Sort 59

Sort operator < 60

functor predicate specified can be a function pointer or a functor which is a class that defines operator() object when instantiated can be used just like a function would be. 61

62

STL - hash_map Hashed Associative Container - associates objects of type Key with objects of type Data. Pair Associative Container - value type is pair <const Key, Data> Unique Associative Container - no two elements have keys that compare equal using EqualKey. Looking up an element by key is efficient - useful for "dictionaries" where order is irrelevant 63

STL - hash_map 64

STL - hash_map Key - hash_map's key type Data - hash_map's data type. HashFcn - hash function used by the hash_map. EqualKey - hash_map key equality function a binary predicate that determines whether two keys are equal. 65