. 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.

Slides:



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

Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 10 SHARED MEMORY.
Dynamic Memory Management
Introduction to Memory Management. 2 General Structure of Run-Time Memory.
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.
Object Oriented Programming Elhanan Borenstein Lecture #12 copyrights © Elhanan Borenstein.
. Virtual Classes & Polymorphism. Example (revisited) u We want to implement a graphics system u We plan to have lists of shape. Each shape should be.
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.
Polymorphism From now on we will use g++!. Example (revisited) Goal: Graphics package Handle drawing of different shapes Maintain list of shapes.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Template class Wrapper { public: T* operator->() { return &myT; } private: T myT; }; int main() { Wrapper wThing; wThing- >Foo(); // calls Thing::Foo()...
. Copying, casting, and more. Example: MyString u Lets put our knowledge of C++ classes to use u Define a class to represent a string u Replace all the.
. Memory Management. Memory Organization u During run time, variables can be stored in one of three “pools”  Stack  Static heap  Dynamic heap.
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.
Review of C++ Programming Part II Sheng-Fang Huang.
Ch 4. Memory Management Timothy Budd Oregon State University.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Programming Languages and Paradigms Object-Oriented Programming.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
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.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
1 Data Structures - CSCI 102 CS102 C++ Pointers & Dynamic Objects Prof Tejada.
Pointers OVERVIEW.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
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.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
The Big Three Based on Weiss “Data Structures and algorithm Analysis CS240 Computer Science II.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Writing Correct C++ Programs without “delete” Huang-Ming Huang CSE332 Guest Lecture Washington University in St. Louis.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Previous lecture Introduction to OOP and C++ Data Abstraction –String example.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 2 2 Call The Project Dynamic-Memory 4 4 # include "Utilities.hpp" int main(int argc, char * argv[]) { short int *PtrNo; (*PtrNo) = 5; printf ("(*PtrNo)
Pointer Variables A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
Memory Management.
C++ Catastrophes “if C allows you to shoot yourself in the foot, then C++ is giving you a machine gun!” James Prince.
Computer Organization and Design Pointers, Arrays and Strings in C
Overview 4 major memory segments Key differences from Java stack
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Memory Management Idioms
Java Review: Reference Types
CMSC 202 Lesson 21 Exceptions II.
Dynamically Allocated Memory
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Overview 4 major memory segments Key differences from Java stack
Overview of Memory Layout in C++
Exceptions 2 CMSC 202.
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
Objects Managing a Resource
Pointer Variables A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer.
Introduction to Data Structures and Software Engineering
Presentation transcript:

. 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 to ensure that allocated memory will be freed when it is no longer in use

Strategy #1: Fixed Ownership u Allocated pointer belongs to the entity (function or objects) that created it u That entity is responsible for freeing the pointer void foo() { char* mem = new char[1000]; … delete [] mem; }

Example: String class class String { public: String( char const *str ) { int l = strlen(str); m_data = new char[l]; memcpy(m_data, str, l); } ~String() { delete [] m_data; } private: char* m_data; };  The memory for char* represented by String is owned by the object u Class encapsulates details of memory management u With careful implementation, this class is memory-tight

Strategy #2: Dynamic ownership (compile time) u Object has an owner u However, owner changes through specific function calls Example: u strdup(s) allocates new memory and transfers it with return value u strdup does not release the memory

Ownership transfer and interface design Design principle: u keep free resources at the same level you allocate them u Reduces memory leaks due to interface problems

Example: design choices ReadLine – read a line of input u char* ReadLine() – returns pointer to newly allocated memory – user has to free it u char* ReadLine() – returns pointer to static buffer – user has to copy line to another buffer u void ReadLine(char* Buffer) – uses a user supplied buffer – ReadLine cannot resize buffer

Strategy #3: Dynamic ownership (run time) u In some case we cannot know who will own a pointer u In other cases, we do not want the programmer to remember who owns what u Can we use an object that “remembers” who owns the object?

Dumb Pointers u Suppose T is a class u T* is a “dumb pointer” supplied by compiler u It remembers the address of the object and allows us to access it, but nothing else u Can we build smarter pointers?

The Pointer Interface To implement a pointer-like object we need: u pointer::pointer( T*) u pointer::pointer( pointer const& ) u pointer& operator=( pointer const& ) u T& pointer::operator*() u T const& pointer::operator*() const u T* pointer::operator->() u T const * pointer::operator->() const u pointer::operator void const*() const

Pointer class template class pointer { public: pointer( T* p = NULL ) : m_ptr(p) {} T& operator*() { return *m_ptr; } … private: T* m_ptr; };

“Smart” Pointers u We can ensure that pointer “cleans up” after itself u Simply add destructor pointer::~pointer() { if( m_ptr != NULL ) delete m_ptr; }  This class is called auto_ptr

Auto_ptr struct bar { … }; void foo() { auto_ptr myBar = new bar; … // use myBar as a pointer … } // myBar is deleted automatically

Auto_ptr in exceptions u Auto_ptrs provide clean mechanism to deal with exception void foo() { auto_ptr myBar = new bar; apple(); // apple might throw an execption … } // myBar is deleted automatically // even if an exception is thrown by apple

Auto_ptr auto_ptr is like a pointer, but not exactly: void foo() { auto_ptr myBar = new bar; … if( … ) { auto_ptr myOtherBar = myBar; … } … } What happens in this example?

Transfer of Ownership u To avoid multiple deletes, auto_ptr ensures that only one auto_ptr points to a certain object u The statement auto_ptr myOtherBar = myBar; transfer the ownership from myBar to myOtherBar  How do we achieve this?

auto_ptr details auto_ptr( auto_ptr& rhs ) : m_ptr( rhs.release() ) {} auto_ptr& operator=( auto_ptr& rhs ) { reset( rhs.release() ); return *this; } void reset(T* p = NULL) { if( m_ptr != p ) delete m_ptr; m_ptr = p; } T* release() { T* tmp = m_ptr; m_ptr = NULL; return tmp; }

Auto_ptr summary u Provide mechanism for transfer of ownerships u Can be dangerous u Requires discipline from programmer u Does not replace the need for pointers  The method T* auto_ptr ::get() allows to access the dumb pointer version of an auto_ptr

Strategy #4: Reference Counting u In some cases, we do not want to establish ownership u Managing ownership within forces us to make unnecessary copies u Can we get away with memory management without authorship? u The general mechanism of reference counting provides one solution

Reference Counting String a = “foo bar”; String b = a; String c = a; The resulting memory structure: foo bar a: b: c: stackheap

Reference counting u Can we do better? Idea: Do not copy value of string u Have all object point to the same memory u How do we know when to free the memory? foo bar a: b: c:

Reference Counting Solution: u Store a reference counter that counts number of pointers u Reference counter shows whether the object is in use a: b: c: 3 foo bar

Reference Counting 1 After Object Creation 1 1 After Object Destruction 3 0 After Last Object Destruction 4 2 After Object Copy 2

String with reference counting u See [String.h]

Example revisited Returning to the ReadLine example u String ReadLine()  returns a String object  A new String is copied on return value  But… the actual memory is not copied  Ownership transfer occur smoothly with minimal overhead

ReadLine Example String ReadLine() { String line; … // do read return line; } void foo() { String a = ReadLine(); … }

General Purpose Reference Counting u See RCPointer.h

Reference Counting u Suppose String has operator[] u Consider the following code String a = “foo bar”; String b = a; String c = a; c[2] = ‘l’; u What does this code do?

Reference Counting u After we modify c, it is no longer identical to a and b u We can no longer save memory by storing all three strings in one place Solution u “Clone on Write” – make a copy of an object when it is modified

Implementing operator[] in String Read-only access: char const& operator[](int i) const { return m_ptr->m_data[i]; } Read/Write access: char & operator[](int i) { if( m_ptr->m_rc > 1 ) { // make a new copy of the string m_ptr->m_rc--; m_ptr = new StringValue( *m_ptr ); } return m_ptr->m_data[i]; }

Clone on Write u Perform the copy operation only when new copy is needed u This is an instance of “lazy evaluation” u How can we perform this in a generic RCPointer?

Template Clone on Write Distinguish between u read only access: T const& RCPointer ::operator*() const; T const* RCPointer ::operator->() const; u and read/write access T& RCPointer ::operator*(); T* RCPointer ::operator->(); In these operations we perform copy

Reference counting and cycles u Reference counting could have been used as an automatic garbage collection in C++. u Problem: Data structures can include cycles. In this case the pointers will never be deleted. If all these pointers were reference counted, then no memory would be freed

When to use what ? u auto_ptr/Ownership transfer:  simple yet problematic. Good for local variables u Reference counting:  Simple, memory safe, efficient, problematic when modifying the object.  Very good for large objects, and STL containers providing these do not change the objects. u Reference counting with Clone On Write:  Optimal for STL, and for large objects. problematic for data structures with cycles.