RAII and Smart Pointers. Ali Malik

Similar documents
Pointers. Developed By Ms. K.M.Sanghavi

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers

Homework 4. Any questions?

C++ Smart Pointers. CSE 333 Autumn 2018

04-17 Discussion Notes

Smart Pointers. Some slides from Internet

CS 241 Honors Memory

Lecture 15a Persistent Memory & Shared Pointers

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

COMP6771 Advanced C++ Programming

Assertions and Exceptions

C++ Programming Lecture 7 Software Engineering Group

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

G52CPP C++ Programming Lecture 16

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

COMP6771 Advanced C++ Programming

Vector and Free Store (Pointers and Memory Allocation)

Object-Oriented Programming for Scientific Computing

Intermediate C++ 1/83

Chapter 17 vector and Free Store. Bjarne Stroustrup

Engineering Robust Server Software

05-01 Discussion Notes

Chapter 17 vector and Free Store

Consider the program...

Chapter 17 vector and Free Store

CS93SI Handout 04 Spring 2006 Apr Review Answers

CSE 333 Lecture smart pointers

Object-Oriented Programming for Scientific Computing

Pointers! Arizona State University 1

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Vector and Free Store (Vectors and Arrays)

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

Pointers, Dynamic Data, and Reference Types

a data type is Types

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

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

vector and Free Store

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

Lecture 2, September 4

Reminder: compiling & linking

Abstract. Vector. Overview. Building from the ground up. Building from the ground up 1/8/10. Chapter 17 vector and Free Store

Programming in C and C++

G52CPP C++ Programming Lecture 17

Ch. 12: Operator Overloading

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

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

G52CPP C++ Programming Lecture 20

COMP 2355 Introduction to Systems Programming

Midterm Review. PIC 10B Spring 2018

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione

CMSC 341 Lecture 7 Lists

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

Classes and Pointers: Some Peculiarities

A Crash Course in (Some of) Modern C++

CS

A brief introduction to C++

G52CPP C++ Programming Lecture 13

Heap Arrays and Linked Lists. Steven R. Bagley

Fast Introduction to Object Oriented Programming and C++

CS201 Some Important Definitions

Unit III Virtual Functions. Developed By Ms. K.M.Sanghavi

Smart Pointers in C++11

Separate Compilation Model

C++ Primer. CS 148 Autumn

Introduction to C++ Part II. Søren Debois. Department of Theoretical Computer Science IT University of Copenhagen. September 12th, 2005

Topics. Constructor. Constructors

These are notes for the third lecture; if statements and loops.

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms

1. Write the number of the definition on the right next to the term it defines. (a) copy 4

377 Student Guide to C++

CS201- Introduction to Programming Current Quizzes

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Financial computing with C++

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

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

Implementing Abstractions

C++ is Evolving. std::array

Heap Arrays. Steven R. Bagley

Written by John Bell for CS 342, Spring 2018

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

The vector Class and Memory Management Chapter 17. Bjarne Stroustrup Lawrence "Pete" Petersen Walter Daugherity Fall 2007

Chapter 18 Vectors and Arrays [and more on pointers (nmm) ] Bjarne Stroustrup

Programmazione. Prof. Marco Bertini

dynamically allocated memory char* x = new char; int* x = new int[n]; ???...?

An Introduction to C++

Variables, Memory and Pointers

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Data Structures and Algorithms for Engineers

A Generic Non-intrusive Smart Pointer Implementation

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

Recap: Pointers. int* int& *p &i &*&* ** * * * * IFMP 18, M. Schwerhoff

C++ Programming Lecture 7 Software Engineering Group

No littering! Bjarne Stroustrup. Morgan Stanley, Columbia University

COMP6771 Advanced C++ Programming

C++ 8. Constructors and Destructors

377 Student Guide to C++

Transcription:

RAII and Smart Pointers Ali Malik malikali@stanford.edu

Game Plan Recap Conversion Operators RAII Smart Pointers

Recap

Initialisation: Initialisation vs Assignment Transforms an object s initial junk data into valid data. Assignment: Replaces existing valid data with other valid data.

Constructors Normal Constructor: What you are used to! Copy Constructor Initialise an instance of a type to be a copy of another instance Copy Assignment Not a constructor Assign an instance of a type to be a copy of another instance

The Rule of Three If you implement a copy constructor, assignment operator, or destructor, you should implement the others, as well

Conversion Operators

Conversion Operators Let you define how a class can be converted to other types. For example, we could define a conversion of the MyVector to a bool to be false if the vector is empty and true otherwise.

Converting to Type works by overloading the Type() operator. Doesn t have a return value. Conversion Operators class MyClass { public: operator Type() { // return something of type Type } }

Conversion Operators An example defining a bool conversion for MyVector : class MyVector { public: operator bool() { return empty(); } }; MyVector v; if(v) { cout << v[0] << endl; }

RAII

Resource Let s first talk about the abstraction of a resource. We will look at file opening and closing in C as a case study.

C File I/O To read a file in C, you need to: 1. Open the file with fopen 2. Read data using fgets 3. Close the open file with fclose If a programmer doesn t remember to close an open file, bad things happen (memory leaks, crashes etc.)

C File I/O You can think of this as a resource. What is a resource? Anything that exists in limited supply. Something you have to acquire and release. Examples: memory, open files, sockets etc.

C File I/O To read a file in C, you need to: 1. Open the file with fopen 2. Read data using fgets 3. Close the open file with fclose If a programmer doesn t remember to close an open file, bad things happen (memory leaks, crashes etc.)

C File I/O To read a file in C, you need to: 1. Open the file with fopen // acquire 2. Read data using fgets 3. Close the open file with fclose If a programmer doesn t remember to close an open file, bad things happen (memory leaks, crashes etc.)

C File I/O To read a file in C, you need to: 1. Open the file with fopen // acquire 2. Read data using fgets 3. Close the open file with fclose // release If a programmer doesn t remember to close an open file, bad things happen (memory leaks, crashes etc.)

Other examples of resources: Resources Acquire Release Files fopen fclose Memory new, new[] delete, delete[] Locks lock, try_lock unlock Sockets socket close

RAII Resource Acquisition Is Initialisation

RAII A modern C++ idiom. When you initialize an object, it should already have acquired any resources it needs (in the constructor). When an object goes out of scope, it should release every resource it is using (using the destructor).

RAII Key points: There should never be a half-ready or half-dead object. When an object is created, it should be in a ready state. When an object goes out of scope, it should release its resources.

RAII Key points: There should never be a half-ready or half-dead object. When an object is created, it should be in a ready state. When an object goes out of scope, it should release its resources. The user shouldn t have to do anything more.

How does C File I/O violate RAII? C File I/O void printfile(const char* name) { // acquire file resource FILE* f = fopen(name, "r"); // print contents of f } // release file resource fclose(f);

How does C File I/O violate RAII? C File I/O void printfile(const char* name) { // acquire file resource FILE* f = fopen(name, "r"); // print contents of f } // release file resource fclose(f);

How does C File I/O violate RAII? C File I/O void printfile(const char* name) { // acquire file resource FILE* f = fopen(name, "r"); // print contents of f // release file resource? }

How does C File I/O violate RAII? C File I/O void printfile(const char* name) { // acquire file resource FILE* f = fopen(name, "r"); } // print contents of f // release file resource? f goes out of scope, but doesn t release its resources.

C File I/O What would be an RAII friendly solution for C File I/O?

C File I/O + RAII class FileObj { public: FILE* ptr; FileObj(char* name) : ptr(fopen(name, "r") {} }; ~FileObj() { fclose(ptr); }

C File I/O Our new printfile method would look like: void printfile(const char* name) { // initialization will acquire resources FileObj fobj(name); // print contents of f } // FileObj destructor will release resources

In fact, you have already been using RAII! For example: C File I/O You can create an ifstream and it will open the file When the ifstream goes out of scope, its destructor closes the file. Don t actually need to call the.close() method.

RAII - An Aside RAII is a bad name for the concept. "The best example of why I shouldn't be in marketing" "I didn't have a good day when I named that" Bjarne Stroustrup, still unhappy with the name RAII in 2012

A better name is probably: RAII - An Aside Constructor Acquires, Destructor Releases or Scope Based Resource Management

Smart Pointers

Smart Pointers What is another thing that violates RAII? Raw Pointers and heap allocation!

Smart Pointers Calls to new acquire resource (memory). Calls to delete release resource. But this is not automatically done when the pointers go out of scope.

Smart Pointers But this is not automatically done when the pointers go out of scope: void rawptrfn() { // acquire memory resource Node* n = new Node; } // manually release memory delete n;

Smart Pointers But this is not automatically done when the pointers go out of scope: void rawptrfn() { // acquire memory resource Node* n = new Node; } // manually release memory delete n; If we forget this, we leak memory.

Smart Pointers What would be an RAII solution to this? Have a class that Allocates the memory when initialized Frees the memory when destructor is called Allows access to underlying pointer

Let s plan and write this up: Smart Pointers Smart Pointers (RAIIPtr_unique.pro)

First we make a smart pointer Smart Pointers SmartPtr<int> x; resource Data (heap)

Smart Pointers We then make a copy of our smart pointer SmartPtr<int> y; resource SmartPtr<int> x; resource Data (heap)

Smart Pointers When y goes out of scope, it deletes the heap data SmartPtr<int> y; resource SmartPtr<int> x; resource Data (heap)

Smart Pointers This leaves x pointing at deallocated data SmartPtr<int> x; resource

Smart Pointers If we dereference x or its destructor calls delete, we crash SmartPtr<int> x; resource

Smart Pointers If we dereference x or its destructor calls delete, we crash SmartPtr<int> x; resource

Smart Pointers Have to be careful when copying an RAII object Don t want two objects thinking they both exclusively own a resource

Smart Pointers C++ already has built-in smart pointers. std::unique_ptr std::shared_ptr std::weak_ptr

unique_ptr Similar to what we wrote earlier Uniquely own its resource and deletes it when the object is destroyed Cannot be copied! { std::unique_ptr<int> p(new int); // Use p } // Freed!

shared_ptr Resource can be stored by any number of shared_ptrs Deleted when none of them point to it { std::shared_ptr<int> p1(new int); // Use p1 { std::shared_ptr<int> p2 = p1; // Use p1 and p2 } // Use p1 } // Freed!

How are these implemented? shared_ptr Reference counting! Store an int that keeps track of the number currently referencing that data Gets incremented in copy constructor/copy assignment Gets decremented in destructor or when overwritten with copy assignment Frees the resource when reference count hits 0

Smart Pointers See Course Reader pg. 351 onwards for details. Let s plan and write this up: Smart Pointers (RAIIPtr_shared.pro)

Used to deal with circular references of shared_ptr Read documentation to learn more! weak_ptr

Next Time Final Topics