Writing Correct C++ Programs without “delete” Huang-Ming Huang CSE332 Guest Lecture Washington University in St. Louis.

Slides:



Advertisements
Similar presentations
Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup
Advertisements

Chapter 18 Vectors and Arrays
Brown Bag #3 Return of the C++. Topics  Common C++ “Gotchas”  Polymorphism  Best Practices  Useful Titbits.
Chapter 18 Vectors and Arrays John Keyser’s Modification of Slides by Bjarne Stroustrup
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
. Smart Pointers. Memory Management u One of the major issues in writing C/C++ code is managing dynamically allocated memory u Biggest question is how.
CSE 332: C++ memory management idioms C++ Memory Management Idioms Idioms are reusable design techniques in a language –We’ll look at 4 important ones.
CSE 332: C++ copy control I Copy Control (Part I) Copy control consists of 5 distinct operations –A copy constructor initializes an object by duplicating.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
The Standard Template Library – part 2. auto_ptr Regular pointers may cause memory leaks Regular pointers may cause memory leaks void f() { SomeClass.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
. Plab – Tirgul 10 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Exceptions David Rabinowitz. March 3rd, 2004 Object Oriented Design Course 2 The Role of Exceptions Definition: a method succeeds if it terminates in.
Plab – Tirgul 8 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Lecture 9 Concepts of Programming Languages
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Review for Midterm Chapter 1-9 CSc 212 Data Structures.
CS352-Week 2. Topics Heap allocation References Pointers.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
CSE 332: C++ memory management idioms C++ Memory Management Idioms Idioms are reusable design techniques in a language –We’ll look at 4 important ones.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Pointers OVERVIEW.
C++ Memory Overview 4 major memory segments Key differences from Java
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
 Managing the heap  Resource acquisition is initialization (RAII)  Overriding operator new and delete  Class-based memory pools.
Object-Oriented Programming in C++
Boost Candy A quick introduction to some libraries.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
CSE 332: Memory management with C++ classes Memory Management with Classes Review: for non-static built-in (native) types –default constructor and destructor.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
PROGRAMMING 1 – HELPER INSTRUCTIONS ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (this Friday). Today: –Templates. –STL –Smart Pointers.
CSCE Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 18: Vectors, Templates and Exceptions 1.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
FASTFAST All rights reserved © MEP Make programming fun again.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Jim Fawcett CSE687-OnLine – Object Oriented Design Summer 2017
Pointers and Dynamic Arrays
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Memory Management with Classes
Overview 4 major memory segments Key differences from Java stack
Jim Fawcett CSE687 – Object Oriented Design Spring 2015
Motivation and Overview
C++ Memory Management Idioms
CSC113: Computer Programming (Theory = 03, Lab = 01)
Lecture 9 Concepts of Programming Languages
Overview 4 major memory segments Key differences from Java stack
Overview of Memory Layout in C++
CSE 333 – Section 10 Final Review.
Objects Managing a Resource
Resource Allocation and Ownership
Lecture 9 Concepts of Programming Languages
Presentation transcript:

Writing Correct C++ Programs without “delete” Huang-Ming Huang CSE332 Guest Lecture Washington University in St. Louis

Computer Architecture int main() { int i = 0; Card c1; …. return 0; }

Memory Model Code Stack Heap int main() { int i = 0; Card c1; …. return 0; } Global

int func() { int i = 1; int j = 2; const char* str=“test”; Card a(“3C”); Card b=a; …. return 0; } Card::Card(const char* s) { …. } Program Execution Model Code SectionStack Section i j 2 a.rank a.suit 3 str 1 CLUBS 0 Card::Card() : rank(NO_RANK), suit(NO_SUIT) { } b.rank NO_RANK NO_SUIT 3 CLUBS b.suit Card b; b=a; Card& Card::operator= (const Card& other) { rank= other.rank; suit = other.suit; } Card::~Card() { } 0x

Program Execution Model with Heap Allocation Game* makeGame(const char* name) { Game* result = 0; if (strcmp(name,”bridge”)==0) result= new BridgeGame; else if (strcmp(name,”hearts”)==0) result= new HeartsGame; return result; } CodeStackHeap 0x4518ab31 hearts name 0result 0x x4518ab31 int strcmp(const char* s1, const char* s2){ …. return result; } 10 1.Find an empty space in heap for HeartsGame. (Time consuming) 2.Execute the constructor of HeartsGame 3.Return the address of the newly created object 0x

Differentiate Stack and Heap Objects Card a_card; //  stack object Destructor will be implicitly called when a_card is out of scope. Card* card_ptr = new Card; //  heap object Requires explicit delete Don’t do these delete &a_card; a_card = *(new Card);

When to use “new”? Objects have to live beyond current scope Is object copying a viable solution? Good for copy : Card objects  Object size is small  Non-polymorphic Bad for copy : Player, Game objects.  Involve heap memory allocation  Polymorphic Is object swapping a good alternative? Good for objects with embedded heap objects such as  Player,  std::string  All STL containers, like  std::vector, std::set, std::map, …, etc. Not useful for polymorphic classes Game* makeGame(const char* name) { Game* result = 0; if (strcmp(name,”bridge”)==0) result= new BridgeGame; else if (strcmp(name,”hearts”)==0) result= new HeartsGame; return result; }

Problem with the interaction between “new” and exception Player* Game::add_player(const char* name) { Player* p = std::find_if(players,player+size, lessThan(name)); if (p != player+size && p->name() ==name) return p; Player* temp = new Player[size+1]; Player* dest = std::copy(players, p, temp); *dest = Player(name); std::copy(p, player+size, dest+1); std::swap(temp, players); delete[] temp; return dest; } players+size name=“Ken” p players Ted Sue Joe Bob p temp Ted Sue dest Ken Joe Bob Could throw exceptions temp won’t be deleted if any exception is thrown

How to fix it? Use “try” and “catch”, delete temp in catch clause if any exception is thrown. If non-thrown swap() is defined for Player class, you can use swap() instead of assignment. Only deal with std::bad_alloc exception Not a solution for other possible exceptions Resource Acquisition is Initialization (RAII)

Resource Acquisition is Initialization (RAII)‏ Referred as “Guard Idiom” by Dr. Gill. However, the term RAII is more widely used in C++ community. Relies on Stack object would be destructed upon out of scope. Use stack object to hold the ownership of a heap object, or any other resource that requires explicit clean up. Heap object ( or resources) is release upon the destruction of the RAII stack object.

RAII Utility Classes template class scoped_ptr { T* ptr; public : scoped_ptr(T* p=0) :ptr(p) {} ~scoped_ptr() { delete ptr; } void reset(T* p) { delete ptr; ptr = p; } T* get() { return ptr;} void swap(scoped_ptr& ); } template class vector { T* ptr; size_t sz; public : vector() :ptr(0), sz(0) {} ~ vector () { delete ptr[]; } … void swap(vector& ); }

How to use RAII Game* game; if (strcmp (argv[1], “bridges”)==0) game = new BridgeGame ; else if (strcmp(argv[1],”hearts”)==0) game = new HeartsGame ; game->add_player(“tom”); game->add_player(“ted”); game->refresh(); game->deal_hands(); game->score_hands(); game->print(); delete game; boost::scoped_ptr game; if (strcmp (argv[1], “bridges”)==0) game.reset(new BridgeGame); else if (strcmp(argv[1],”hearts”)==0) game.reset(new HeartsGame); game->add_player(“tom”); game->add_player(“ted”); game->refresh(); game->deal_hands(); game->score_hands(); game->print();

Stock Smart Pointers Boost ( scoped_ptr shared_ptr weak_ptr std auto_ptr

boost::scoped_ptr Used for a single object, not for array Noncopyable scoped_ptr game1(new BridgeGame); // OK scope_ptr game2(game1); // Won’t compile scoped_ptr game3; // OK game3 = game1; // Won’t compile game3.reset(new BridgeGame); // OK game3.swap(game1); // OK Useful to implement pointer to implementation (pimple) idiom.

C++ Pimple idiom (Conceptual View)

C++ Pimple idiom (implementation View) /// Foo.h #include struct FooImpl; // forward declaration class Foo { using namespace boost; scoped_ptr pimpl; public: Foo(); void method1(); }; /// Foo.cc #include “Foo.h” struct FooImpl { int state; … }; Foo::Foo() : pimpl(new FooImpl) { } void Foo::method1() { ++ pimpl->state; … }

Why use pimple idiom Separation between interface and implementation Allows library vendors keep implementation detail secrete Avoid client recompilation for the change of internal data structure. Exception safety

std::auto_ptr Similar to scoped_ptr, but copyable. Copy represents ownership transfer. Best used for function parameters and return types in the case when ownership transfer is needed. auto_ptr makeGame(const char* name) { if (strcmp(name, “bridge”) ==0) return auto_ptr (new BridgeGame); else if (strcmp(name, “hearts”) == 0) return auto_ptr (new HeartsGame); return auto_ptr (); }

boost:shared_ptr Reference counting semantics. Simplest form of garbage collection a : share_ptr ptr pcount :Foo 1 : int Class View Object View b : share_ptr ptr pcount shared_ptr a(new Foo); shared_ptr b = a; 2 : int 0 : int

Reference Counting and Cyclic Dependency Problem

void fun() { shared_ptr cse(new Department); shared_ptr cse332(new Course); cse332.department = cse; cse.courses.push_back(cse332); } cse cse332 : Department: Course 1 : int coursesdepartment 2 : int courses[0] 2 : int

Boost::weak_ptr Used together with shared_ptr to avoid cyclic reference counting problem. Does not increase reference count during construction and copying. Class Department { vector > courses; }; Class Course { weak_ptr department; }; void fun() { shared_ptr cse(new Department); shared_ptr cse332(new Course); cse332.department = cse; cse.courses.push_back(cse332); } The reference count is not incremented

Collection of Objects Player* players = new Player[size]; Need explicit delete statement for players array vector players; Expensive Player object copying vector players; May require explicit delete statement for each individual Player object vector > and vector > won’t compile. because all containers in C++ standard requires that any element a and b in the container, After a = b then a == b

Collection of Objects vector > players Ownership to Player objects are not exclusive Comparing to vector, it incurs small overhead for reference counting. No need for explicit delete statement. boost::ptr_vector players; Only heap objects can be added to the container. It has the exclusively ownership for the objects it contains. No need for explicit delete statement.

Preferred Form for Object Collections vector, vector Contained objects are cheap to copy ptr_vector, ptr_vector Contained objects are expensive to copy or polymorphic. vector > or vector > The ownership of the contained object cannot be exclusively held.

Summary Dynamic memory allocation are expensive, avoid it if you can. Be careful with implicit object copying. Don’t write code that requires explicit “delete” statement. For single object : use smart pointers For collection of value types : use standard container classes For collection of pointers : use boost ptr containers or shared_ptr.