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.

Slides:



Advertisements
Similar presentations
1.00 Lecture 37 A Brief Look at C++: A Guide to Reading C++ Programs.
Advertisements

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
. 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.
The Standard Template Library – part 2. auto_ptr Regular pointers may cause memory leaks Regular pointers may cause memory leaks void f() { SomeClass.
Chapter 15 Memory Management: Four main memory areas for a C++ program: Code: code for instructions, methods, etc. static data: Global variables (declared.
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.
. 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.
Template class Wrapper { public: T* operator->() { return &myT; } private: T myT; }; int main() { Wrapper wThing; wThing- >Foo(); // calls Thing::Foo()...
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Dynamically Allocated Arrays May 2, Quiz 5 Today.
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.
CS 225 Lab #2 - Pointers, Copy Constructors, Destructors, and DDD.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Ch 4. Memory Management Timothy Budd Oregon State University.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
1 Data Structures - CSCI 102 CS102 C++ Pointers & Dynamic Objects Prof Tejada.
Memory Management Issues, Solutions, and Examples.
1 Inside the Vector Class: with additional needed methods CPS212CPS212 Gordon College.
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.
Dynamically Allocated Arrays December 4, Skip the Rest of this PowerPoint.
Object-Oriented Programming in C++
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
Writing Correct C++ Programs without “delete” Huang-Ming Huang CSE332 Guest Lecture Washington University in St. Louis.
CS 1704 Introduction to Data Structures and Software Engineering.
Objects and Variables Local variables – Confined to single context: allocated on stack – Primitive types such as int or object references – Must be initialized.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
CSE 332: Memory management with C++ classes Memory Management with Classes Review: for non-static built-in (native) types –default constructor and destructor.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
Pointers and References. Pointers & Memory 0x000x040x080x0B0x100x140x180x1B0x20.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Pointers and Dynamic Arrays
Learning Objectives Pointers as dada members
Jim Fawcett CSE687 – Object Oriented Design Spring 2001
Memory Management with Classes
Overview 4 major memory segments Key differences from Java stack
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Motivation and Overview
C++ Memory Management Idioms
Making Dynamic Memory Allocation Safer
Dynamic Memory CSCE 121 J. Michael Moore.
Memberwise Assignment / Initialization
CMSC 202 Lesson 21 Exceptions II.
Overview 4 major memory segments Key differences from Java stack
Overview of Memory Layout in C++
Exceptions 2 CMSC 202.
Dynamic Memory Management
Objects Managing a Resource
Introduction to Data Structures and Software Engineering
Class: Special Topics 2 For classes using memory allocation
Dynamic Memory CSCE 121.
Dynamic Memory Management
Exceptions.
Copy Constructors and Overloaded Assignment
CSE 333 – Section 5 C++ (1m).
Presentation transcript:

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 in C++ Copy constructor trick for assignment –Ensures release of existing resource and acquisition of the new resource both succeed or fail together RAII (a.k.a. Guard) –ties dynamic resources to other (esp. automatic) scopes Reference counting –ties dynamic lifetime to a group of references Copy-on-write –allows more efficient management of multiple aliasing

CSE 332: C++ memory management idioms Copy Constructor Trick for Assignment Cleanup/assignment succeed or fail together class Array { public: Array(unsigned int) ; Array(const Array &); // assume copy constructor makes a deep copy ~Array(); Array & operator=(const Array &a); private: int * ints_; size_t size_; }; Array & Array::operator=(const Array &a) { if (&a != this) { Array temp(a); std::swap(temp.ints_, ints_); std::swap(temp.size_, size_); } return *this; }

CSE 332: C++ memory management idioms Resource Acquisition Is Initialization (RAII)‏ Also referred to as the “Guard Idiom” –However, the term “RAII” is more widely used in C++ Relies on the fact that in C++ a stack object’s destructor is called when stack frame pops Idea: we can use a stack object to hold the ownership of a heap object, or any other resource that requires explicit clean up –Initialize stack object when the resource is allocated –De-allocate resource in the stack object’s destructor

CSE 332: C++ memory management idioms Example: C++ auto_ptr Class Template RAII idiom example C++ has an auto_ptr class template #include using namespace std; auto_ptr assumes ownership of aliased X auto_ptr destructor calls delete on the pointer to the owned X Call release to break ownership by auto_ptr when it’s safe to do so Combines well with other memory idioms Foo *createAndInit() { Foo *f = new Foo; auto_ptr p(f); init(f);// may throw exception p.release(); return f; } int run () { try { Foo *d = createAndInit(); } catch (...) { }

CSE 332: C++ memory management idioms More About auto_ptr and RAII auto_ptr copy constructor transfers ownership from the older to the newer one –E.g., if you pass an auto_ptr by value to a function –E.g., if you return an auto_ptr by value as a function result Ownership is passed along a chain of calls Makes sure it’s cleaned up where chain ends auto_ptr createAndInit() { auto_ptr p(new Foo); p = init(p); // may throw exception return p; } int run () { try { auto_ptr q(createAndInit()); // do something with object return 0; } catch (...) { return 1; }

CSE 332: C++ memory management idioms Introduction to Reference Counting Basic Problem –Resource sharing is often more efficient than copying –But it’s hard to tell when all are done using a resource –Must avoid early deletion –Must avoid leaks Solution Approach –Share both the resource and also a counter –Each new reference increments the counter –When a reference is done, it decrements the counter –When count drops to zero, delete resource and counter –“last one out shuts off the lights” Resource counter == 3 reference

CSE 332: C++ memory management idioms Introduction to Copy on Write Basic Problem –Reference counting enables safe and efficient sharing –But what if modifications are made to the resource? –May want logically separate copies of resource Solution –Start with reference counting –Writer checks for count > 1 Copies reference & counter Updates both counters Performs the write –Readers all share a copy, each writer can get its own Resource counter == 2 reference Resource 2 counter == 1 write()

CSE 332: C++ memory management idioms Caution: Containers and Smart Pointers STL containers pose a special problem –Keep contents by value, assign and copy at will –Behavior of auto_ptrs works fine in functions … –… but won’t work within a vector (risks a crash!) How to use smart pointers in containers? –Need a better suited type of smart pointer –Can write one that does reference counting –Other good ideas are found in the boost library

CSE 332: C++ memory management idioms Summary: Memory Management Tips Know what goes where in memory Understand mechanics of stack and heap allocation Watch for simple (and complex) lifetime errors Think about shallow copy vs. deep copy (problems and performance trade-offs) Master useful idioms for C++ memory management –Learn how they work –Understand when to apply them –Look for ways to apply them in the labs and beyond