Pointers. Developed By Ms. K.M.Sanghavi

Similar documents
Pointers. Pointers. Pointer Variables. Pointers

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

Smart Pointers. Some slides from Internet

RAII and Smart Pointers. Ali Malik

COMP6771 Advanced C++ Programming

Lecture 15a Persistent Memory & Shared Pointers

CSE 333 Lecture smart pointers

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

CSE 333 Lecture smart pointers

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

Homework 4. Any questions?

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

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!

ALL ABOUT POINTERS C/C++ POINTERS

Pointers! Arizona State University 1

Object-Oriented Programming for Scientific Computing

Short Notes of CS201

C++ Programming Lecture 7 Software Engineering Group

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

04-19 Discussion Notes

CS201 - Introduction to Programming Glossary By

CA341 - Comparative Programming Languages

C++ Smart Pointers. CSE 333 Autumn 2018

04-17 Discussion Notes

Object-Oriented Programming for Scientific Computing

Assertions and Exceptions

CSE 333 Lecture smart pointers

Pointers, Dynamic Data, and Reference Types

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

Midterm Review. PIC 10B Spring 2018

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

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Smart Pointers - What, Why, Which?

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

CS201 Some Important Definitions

C++ is Evolving. std::array

Smart Pointers, deleted functions, and 2-3 trees

Consider the program...

AN OVERVIEW OF C++ 1

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

G52CPP C++ Programming Lecture 16

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Variables, Memory and Pointers

MM1_ doc Page E-1 of 12 Rüdiger Siol :21

More Tutorial on C++:

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

G52CPP C++ Programming Lecture 20

Assignment operator string class c++ Assignment operator string class c++.zip

COMP 2355 Introduction to Systems Programming

Object Oriented Software Design II

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Programmazione. Prof. Marco Bertini

Intermediate Programming, Spring 2017*

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione

G52CPP C++ Programming Lecture 13

Advanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const.

Introducing C++ to Java Programmers

Smart Pointers in C++11

Homework #3 CS2255 Fall 2012

Fast Introduction to Object Oriented Programming and C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to 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

Linked List using a Sentinel

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor

CS 376b Computer Vision

CS 103 Unit 11. Linked Lists. Mark Redekopp

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Financial computing with C++

C++11 and Compiler Update

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

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

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

Using C++11 s Smart Pointers

Vector and Free Store (Vectors and Arrays)

CS201- Introduction to Programming Current Quizzes

CPSC 427: Object-Oriented Programming

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Outline. A C++ Linked Structure Class A C++ Linked List C++ Linked Dynamic Memory Errors In-class work. 1 Chapter 11: C++ Linked Structures

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

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

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

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

Memory Management: The Details

CS24 Week 3 Lecture 1

Vector and Free Store (Pointers and Memory Allocation)

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

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

Modernizing legacy C++ code

Advanced Systems Programming

C++ Primer. CS 148 Autumn

OBJECT ORIENTED PROGRAMMING

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Transcription:

Pointers Developed By Ms. K.M.Sanghavi

Memory Management : Dynamic Pointers Linked List Example Smart Pointers Auto Pointer Unique Pointer Shared Pointer Weak Pointer

Memory Management In order to create an array in C/C++ you have to know its size in advance during compile time, in other words it has to be a constant int size; cout << Enter size of array : ; cin >> size; int array[size]; // ERROR size has to be a constant Solution in C++, use vector class from the STL which is expandable

Memory Management Date* void CreateDate() // allows the user to create a date object int day, month, year; char dummy; cout << Enter dd/mm/yyyy : ; cin >> day >> dummy >> month >> dummy >> year; Date date(day, month, year); return &date; // ERROR!! Scope of date ends with end of function Date *ptr; ptr=createdate(); // call CreateDate() to generate a new date cout << You entered << *ptr << endl; // variable to which ptr points no longer exist, segmentation fault!!!

Memory Management The new operator in C++ can be used to create objects that can be used after returning from a function Objects allocated in dynamic memory are called heap objects or to be on free store and have a permament existence Date* CreateDate() // allows the user to create a date object int day, month, year; char dummy; cout << Enter dd/mm/yyyy : ; cin >> day >> dummy >> month >> dummy >> year; Date *tmpptr = new Date date(day, month, year); return tmpptr; // returns pointer to heap object Date *ptr; ptr=createdate(); // call CreateDate() to generate a new date cout << You entered << *ptr << endl; // ok, ptr refers to heap object

Memory Management New can also be used to allocate blocks of memory The delete operator is used to release the memory allocated with new once it is no longer needed #include <cstring> char *str = This is an old C-style string ; int len=strlen(str); // computes the length of str char *ptr; // create a pointer to char ptr = new char[len+1]; // set aside memory string + \0 strcpy(ptr,str); // copy str to new memory cout << ptr= << ptr << endl; delete [] ptr; // release ptr s memory

Linked List Example struct link // one element of list int data; // data item link *next; // pointer to next element ; class linklist private: link* first; // pointer to first link public: linklist() first = NULL; // no argument constructor void additem(int d); // add data item (one link) void display(); // display all links

Linked List Example void linklist::additem(int d) // add data item link* newlink = new link; // create a new link newlink->data = d; // give it data d newlink->next=first; // it points to the next link first = newlink; // now first points to this link void linklist::display() // display all links link* current=first; // set ptr to first link while(current!= NULL) // until ptr points beyond last link cout << current->data << ; // print data current=current->next; // move to next link

Smart Pointers Consider the following simple C++ code with normal pointers. MyClass *ptr = new MyClass(); ptr->dosomething(); // We must do delete(ptr) to avoid memory leak Using smart pointers, we can make pointers to work in way that we don t need to explicitly call delete.

Smart Pointers Smart pointer is a wrapper class over a pointer with operator like * and -> overloaded. The objects of smart pointer class look like pointer, but can do many things that a normal pointer can t like automatic destruction reference counting and more. The idea is to make a class with a pointer, destructor and overloaded operators like * and ->.

Smart Pointers Since destructor is automatically called when an object goes out of scope, the dynamically allocated memory would automatically deleted (or reference count can be decremented).

Example for Smart Pointers #include<iostream> using namespace std; class SmartPtr int *ptr; // Actual pointer public: // Constructor explicit SmartPtr(int *p = NULL) ptr = p;

Example for Smart Pointers // Destructor ~SmartPtr() delete(ptr); // Overloading dereferencing operator int &operator *() return *ptr; int *operator ->() //Overloading Access operator return ptr; ;

Example for Smart Pointers int main() SmartPtr ptr(new int()); *ptr = 20; cout << *ptr; // We don't need to call delete ptr: when the object // ptr goes out of scope, destructor for it is automatically // called and destructor does delete ptr. return 0;

Use of Smart Pointers Automatic cleanup. Automatic initialization Ownership transfer Reference counting To shorten allocation and deallocation time. Since C++ does not provide automatic garbage collection like some other languages, smart pointers can be used for that purpose.

Smart Pointers We can make Smart pointers to work on all types. For this we need to use Templates (covered in next unit) C++ libraries provide implementations of smart pointers in the form of auto_ptr : deprecated unique_ptr : Same as auto_ptr shared_ptr and weak_ptr All these pointers exist in <memory> header file

Unique Pointers unique_ptr is a container for a raw pointer, which the unique_ptr is said to own. A unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment), But the std::move function can be used to transfer ownership of the contained pointer to another unique_ptr. A unique_ptr cannot be copied because its copy constructor and assignment operators are explicitly deleted.

Unique Pointers std::unique_ptr<int> p1(new int(5)); std::unique_ptr<int> p2 = p1; //Compile error. std::unique_ptr<int> p3 = std::move(p1); //Transfers ownership. p3 now owns the memory and p1 is rendered invalid. p3.reset(); //Deletes the memory. p1.reset(); //Does nothing.

Shared Pointers Shared_ptr is a container for a raw pointer. It maintains reference counting ownership of its contained pointer in cooperation with all copies of the shared_ptr. An object referenced by the contained raw pointer will be destroyed when and only when all copies of the shared_ptr have been destroyed.

Shared Pointers std::shared_ptr<int> p1(new int(5)); std::shared_ptr<int> p2 = p1; //Both now own the memory. p1.reset(); //Memory still exists, due to p2. p2.reset(); //Deletes the memory, since no one else owns the memory.