C++ Memory Management Idioms

Slides:



Advertisements
Similar presentations
. 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.
Advertisements

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.
Chapter 15 Memory Management: Four main memory areas for a C++ program: Code: code for instructions, methods, etc. static data: Global variables (declared.
CS 225 Lab #2 - Pointers, Copy Constructors, Destructors, and DDD.
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.
CSE333 SECTION 7. Midterm Debrief Hex View 1. Find a hex editor. 2. Learn ‘goto offset’ command. 3. See HW3 pictures. The header: Magic word Checksum.
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.
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.
1 Data Structures - CSCI 102 CS102 C++ Pointers & Dynamic Objects Prof Tejada.
C++ Memory Overview 4 major memory segments Key differences from Java
 Managing the heap  Resource acquisition is initialization (RAII)  Overriding operator new and delete  Class-based memory pools.
Writing Correct C++ Programs without “delete” Huang-Ming Huang CSE332 Guest Lecture Washington University in St. Louis.
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.
On dynamic memory and classes ● We previously had only discussed dynamic memory in regards to structs and dynamic arrays. ● However, they can be used (to.
Memory Management.
Chapter 2 Objects and Classes
Exceptions handling Try, catch blocks Throwing exceptions.
Pointers and Dynamic Arrays
Learning Objectives Pointers as dada members
Exceptions David Rabinowitz.
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
Programming with ANSI C ++
Making Dynamic Memory Allocation Safer
Dynamic Memory CSCE 121 J. Michael Moore.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Memberwise Assignment / Initialization
This pointer, Dynamic memory allocation, Constructors and Destructor
CMSC 202 Lesson 21 Exceptions II.
Chapter 2 Objects and Classes
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Overview 4 major memory segments Key differences from Java stack
understanding memory usage by a c++ program
Chapter 15 Pointers, Dynamic Data, and Reference Types
Smart Pointers.
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Overview of Memory Layout in C++
Exceptions 2 CMSC 202.
Destruction and Copying
Indirection.
Practical Session 4 Rule of 5 R-value reference Unique pointer
CISC/CMPE320 - Prof. McLeod
Dynamic Memory Management
Objects Managing a Resource
9-10 Classes: A Deeper Look.
C++ Constructor Insanity CSE 333 Summer 2018
Destructor CSCE 121.
Resource Allocation and Ownership
Passing Arguments and The Big 5
Destruction and Copying
Dynamic Memory Allocation
Introduction to Data Structures and Software Engineering
Class: Special Topics 2 For classes using memory allocation
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Dynamic Memory CSCE 121.
Dynamic Memory Management
Rule of Three Part 1 & 2.
Exceptions.
Automating Memory Management
CS 144 Advanced C++ Programming April 30 Class Meeting
9-10 Classes: A Deeper Look.
Copy Constructors and Overloaded Assignment
Presentation transcript:

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

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;

C++11 Smart Pointers C++11 deprecates an older smart pointer template auto_ptr : can guard dynamically allocated memory and pass ownership around, but doesn’t work with the STL containers and has other limitations C++11 provides 3 new smart pointer templates instead shared_ptr : a general purpose reference counted guard for dynamic memory (we’ll mostly use this one in this course) weak_ptr : gives access to a resource that is guarded by a shared_ptr without increasing reference count (can be used to prevent memory leaks due to circular references) unique_ptr : a more complex but potentially very efficient way to transfer ownership of dynamic memory safely (implements C++11 “move semantics”)

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

RAII Example: Guarding Newly Allocated Object RAII idiom example via shared_ptr class template #include <memory> using namespace std; shared_ptr<X> assumes and maintains ownership of aliased X Can access the aliased X through it (*spf) shared_ptr destructor calls delete on the pointer to the owned X when it’s safe to do so (per reference counting idiom discussed next) Combines well with other memory idioms shared_ptr<Foo> createAndInit() { Foo *f = new Foo; shared_ptr<Foo> p(f); init(f);// may throw exception return p; } int run () { try { shared_ptr<Foo> spf = createAndInit(); cout << “*spf is ” << *spf; } catch (...) { return -1 return 0;

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” reference reference Resource reference counter == 3

Reference Counting Example: Sharing an Object shared_ptr<Foo> createAndInit() { Foo *f = new Foo; shared_ptr<Foo> p(f); init(f);// may throw exception return p; } int run () { try { shared_ptr<Foo> spf = createAndInit(); shared_ptr<Foo> spf2 = spf; // object destroyed after // both spf and spf2 go away } catch (...) { return -1 return 0; RAII idiom example via shared_ptr class template #include <memory> using namespace std; shared_ptr<X> assumes ownership of aliased X shared_ptr<X> copy constructor increases count, and its destructor decreases count shared_ptr destructor calls delete on the pointer to the owned X when count drops to 0

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 write() Resource 2 reference counter == 1 Resource reference counter == 2 reference

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 C++11 smart pointers (especially shared_ptr) very helpful