Project. C++: Smart Pointers. The Plan. Announcement. Memory Leak. Pointer Ownership. Today: STL 1 Wednesday: STL 2 Thursday: Smart Pointers

Similar documents
Smart Pointers - What, Why, Which?

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

ALL ABOUT POINTERS C/C++ POINTERS

Smart Pointers. Some slides from Internet

Pointers. Developed By Ms. K.M.Sanghavi

Project. C++: Inheritance III. Plan. Project. Before we begin. The final exam. Advanced Topics. Project. This week in the home stretch

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

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

CSCI-1200 Data Structures Spring 2018 Lecture 25 Garbage Collection & Smart Pointers

Copy Control 2008/04/08. Programming Research Laboratory Seoul National University

COMP6771 Advanced C++ Programming

Consider the program...

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

RAII and Smart Pointers. Ali Malik

Chapter 13: Copy Control. Overview. Overview. Overview

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

COMP 2355 Introduction to Systems Programming

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

G52CPP C++ Programming Lecture 20

Project #1: Tracing, System Calls, and Processes

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

QUIZ. How could we disable the automatic creation of copyconstructors

CSE 333 Lecture smart pointers

CMSC202 Computer Science II for Majors

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

QUIZ. How could we disable the automatic creation of copyconstructors

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

CSE 333 Lecture smart pointers

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

StackVsHeap SPL/2010 SPL/20

Common Misunderstandings from Exam 1 Material

COMP 524 Spring 2018 Midterm Thursday, March 1

CS 241 Honors Memory

Smart Pointers in C++11

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

CSI33 Data Structures

Item 3: Predicates, Part 2: Matters of State

Lecture 15a Persistent Memory & Shared Pointers

CS 101: Computer Programming and Utilization

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

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

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

CS250 Final Review Questions

QUIZ Friends class Y;

Class Information ANNOUCEMENTS

G52CPP C++ Programming Lecture 13

Modernizing legacy C++ code

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

CSE 333 Lecture smart pointers

Assignment 1: SmartPointer

Java: introduction to object-oriented features

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Name: Username: I. 10. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

EL2310 Scientific Programming

Ch. 12: Operator Overloading

EL2310 Scientific Programming

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability.

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Smart Pointers, deleted functions, and 2-3 trees

Administrivia. CMSC433, Fall 2001 Programming Language Technology and Paradigms. Administrivia (cont.) Project 1. Copy constructor.

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Implementing Abstractions

Object-Oriented Programming for Scientific Computing

CSCI-1200 Data Structures Fall 2018 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

ECE Object-Oriented Programming using C++ and Java

Pointers! Arizona State University 1

CSCI 262 Data Structures. The Big 3. Copy Constructor. Destructor. Assignment Operator 3/4/ The Big 3

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

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

Praktikum: Entwicklung interaktiver eingebetteter Systeme

CMSC 132: Object-Oriented Programming II

C++FA 6.1 PRACTICE FINAL EXAM

CS105 C++ Lecture 7. More on Classes, Inheritance

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

C++ Programming Lecture 7 Software Engineering Group

Memory and C++ Pointers

Allocation & Efficiency Generic Containers Notes on Assignment 5

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

Introducing C++ to Java Programmers

Problem Set 1. You might want to read Chapter 12 of the course reader before attempting this problem.

Mobile Application Development

Engineering Robust Server Software

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

Discussion Week 1. TA: Kyle Dewey. Sunday, September 25, 11

Garbage Collection Techniques in C++

6 Architecture of C++ programs

CS250 Final Review Questions

Dynamic Memory Allocation

Pointers and memory Nov 17, Ch 9 & 13.1

Pointers review. int a = 5; int *ptr = &a; cout << *ptr;

Transcription:

Project C++: Smart Pointers Takeaway submitted. Next submission: Nim Oct 26 th Remember: okay to change framework Make sure all games work with framework Memory checks Your program should do proper memory management! Questions Announcement Final exam Tuesday, November 18 th 12:30pm 2:30pm Rm 70-3690 The Plan Today: STL 1 Wednesday: STL 2 Thursday: Smart Pointers Memory Leak A bug in a program that prevents it from freeing up memory that it no longer needs. As a result, the program grabs more and more memory until it finally crashes because there is no more memory left. In short: Allocating without cleaning up. Pointer Ownership Everything that is a pointer should be owned Responsible for cleanup when finished Should be known to programmer Should be by design during implementation. Owner and only owner should perform a delete.

Dangling Pointers Pointer is pointing to something that it shouldn t be. Can happen if: If the scope of a pointer extends beyond that of the object being pointed to i.e Returning a pointer to a local variable. If a dynamically allocated memory cell is freed explicitly and then the pointer pointing to such a space is used in subsequent code. Getting around these problems The smart pointer Prevents memory leaks and dangling pointers Wrapper class that owns a pointer to an object Smart pointer ptr The Smart Pointer The Smart Pointer The smart pointer should look and act like a regular pointer: Should support -> Should support * Should be smarter than your average pointer. Reduce memory leaks Reduce dangling pointers Take ownership STL has a standard smart pointer that is a wrapper around a regular pointer class T* ptr; public: explicit (T* p = 0) : ptr(p) ~() delete ptr; T& operator*() return *ptr; T* operator->() return ptr; //... ; What makes smart is that it takes ownership of the pointer and cleans up class T* ptr; public: explicit (T* p = 0) : ptr(p) ~() delete ptr; T& operator*() return *ptr; T* operator->() return ptr; //... ;

Using Instead of void foo() MyClass* p(new MyClass); p->dosomething(); delete p; Use void foo() <MyClass> p(new MyClass); p->dosomething(); p will cleanup after itself Automatic cleanup Reduces memory leaks Automatic initialization Includes a default constructor that sets pointer to NULL Avoid dangling pointers Dangling pointers MyClass* p(new MyClass); MyClass* q = p; delete p; p->dosomething(); // Watch out! p is now dangling! p = NULL; // p is no longer dangling q->dosomething(); // Ouch! q is still dangling! Dangling pointers can be avoided by redefining assignment <T>& <T>::operator=(<T>& rhs) if (this!= &rhs) delete ptr; ptr = rhs.ptr; rhs.ptr = NULL; return *this; Other things that can be done during assignment p = q Create a new copy Ownership transfer use this mechanism Reference Counting Pointed object maintains count Reference Linking Smart pointer maintains count Copy on write Reference Counts Maintaining the Reference Count The reference count will change when: Smart pointer is constructed Smart pointer is copy constructed Smart pointer is assigned to a new SmartPointer. SmartPointer s destructor is called..

The Smart Pointer Maintaining the Reference Count Meaning the smart pointer must define Constructor Copy constructor operator= Destructor For efficiency s sake (this IS C++), all containers will store their objects by value. Note: the smart pointer is a friend to the class of pointers that it is managing. Questions? Funny thing about C++ Inheritance You can only gain polymorphic behavior on pointers (or references) to objects an not on objects themselves. Vehicle V = Car (); // not allowed Vehicle *V = new Car (); // okay class Base /*...*/ ; class Derived : public Base /*...*/ ; Base b; Derived d; vector<base> v; v.push_back(b); // OK v.push_back(d); // error vector<base*> v; v.push_back(new Base); // OK v.push_back(new Derived); // OK too // cleanup: you must do explicitly! for (vector<base*>::iterator i = v.begin(); i!= v.end(); ++i) delete *i; Using smart pointers: vector< linked_ptr<base> > v; v.push_back(new Base); // OK v.push_back(new Derived); // OK too // cleanup is automatic

Another problem with maintaining maps of pointers to objects. These STL classes will compare the items placed in them Meaning that actual pointer values (memory addresses) will be compared What we would like instead is to compare the objects being pointed to. Smart pointers can be extended to provide this. How? By redefining operator< Warning: STL containers may copy and delete their elements behind the scenes all copies of an element must be equivalent Should only use reference counting smart pointers with STL containers Questions? Smart Pointers How can I get them The only Standard smart pointer (STL) is the Copies are not equivalent Uses ownership method on copy Other smart pointers (reference counting) are available from Web page previously referenced. Summary Smart Pointers Wrapper class on a pointer Standard smart pointer: Takes ownership of pointer Reduce memory leaks Reduce dangling pointer Comparison operator for use in STL classes. Use with caution Questions? Have a nice weekend.