Template class Wrapper { public: T* operator->() { return &myT; } private: T myT; }; int main() { Wrapper wThing; wThing- >Foo(); // calls Thing::Foo()...

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Chapter 18 Vectors and Arrays
Chapter 6 Data Types
. 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.
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.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
. Plab – Tirgul 10 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Plab – Tirgul 8 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
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.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 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.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
CS212: Object Oriented Analysis and Design Lecture 4: Objects and Classes - I.
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.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Technical Module : Pointers #1 2000/01Scientific Computing in OOCourse code 3C59 Technical Module : Pointers In this module we will cover Pointers to primitives.
CS162 - Topic #11 Lecture: Recursion –Problem solving with recursion –Work through examples to get used to the recursive process Programming Project –Any.
Recap Visual Perception and Data Visualization Types of Information Display Examples of Diagrams used for Data Display Planning Requirement for Data Visualization.
Memory Management Issues, Solutions, and Examples.
C++ Memory Overview 4 major memory segments Key differences from Java
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
1 Chapter 15-2 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Object-Oriented Programming in C++
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Dynamic Memory Review l what is static, automatic, dynamic variables? Why are dynamic(ally allocated) variables needed l what is program stack? Function.
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 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (this Friday). Today: –Templates. –STL –Smart Pointers.
Data Types Chapter 6: Data Types Lectures # 13. Topics Chapter 6: Data Types 2 Introduction Primitive Data Types Character String Types Array Types Associative.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Memory Management.
Exceptions handling Try, catch blocks Throwing exceptions.
Object Lifetime and Pointers
User-Written Functions
Module 9: Memory and Resource Management
Day 03 Introduction to C.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Java Programming Language
Pointers, Polymorphism, and Memory Allocation
C++ Memory Management Idioms
Making Dynamic Memory Allocation Safer
Day 03 Introduction to C.
Pointers Revisited What is variable address, name, value?
CS212: Object Oriented Analysis and Design
Dynamic Memory CSCE 121 J. Michael Moore.
Chapter 15 Pointers, Dynamic Data, and Reference Types
9-10 Classes: A Deeper Look.
Exceptions handling Try, catch blocks Throwing exceptions.
Dynamic Memory.
Introduction to Data Structures and Software Engineering
Dynamic Memory CSCE 121.
9-10 Classes: A Deeper Look.
Presentation transcript:

template class Wrapper { public: T* operator->() { return &myT; } private: T myT; }; int main() { Wrapper wThing; wThing- >Foo(); // calls Thing::Foo()... } Smart - > Pointers * BY: GLENN WHEELER AND MOHAMED SHAIKH

Smart Pointers Introduction What are they? An example of Smart Pointers Benefits of Smart Pointers Conclusion

Introductions In programming, the use of pointers are the main source of errors (or bugs) when developing code. The main problem found are the occurrences of memory leaks, this is due to the way pointers interact with memory, such as allocation and deallocation, which when performed inefficiently can cause the pointer to hang (or dangle, meaning that the pointer points to a previous removed object). The solution to this dilemma is the use of Smart Pointers.

What are Smart Pointers? Smart Pointers look the same as normal pointers and utilise the same interfacing operations such as dereferencing (*) and indirection (->) yet carry other functionality. Smart pointers reduce bugs and retain efficiency and control memory management by automated methods.

These automated methods apply to such things as allocation and deallocation of resources in the effort of eliminating memory leaks. What are Smart Pointers? template class auto_ptr { T* ptr; public: explicit auto_ptr(T* p = 0) : ptr(p) {} ~auto_ptr() {delete ptr;} T& operator*() {return *ptr;} T* operator->() {return ptr;} };

An Example of Smart Pointers Within the standard C++ library is an example of a really simple smart pointer implementation. This example, auto_ptr, demonstrates memory management and is found within the memory header file.

template class auto_ptr { T* ptr; public: explicit auto_ptr(T* p = 0) : ptr(p) {} ~auto_ptr() {delete ptr;} T& operator*() {return *ptr;} T* operator->() {return ptr;} }; An Example of Smart Pointers

Therefore instead of writing… void foo() { MyClass* p(new MyClass); p->DoSomething(); delete p; } Therefore user writes… void foo() { auto_ptr p(new MyClass); p->DoSomething(); }

An Example of Smart Pointers Here is an sample of code which illustrates the situation of a dangling pointer… 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!

An Example of Smart Pointers For auto_ptr, this is solved by setting its pointer to NULL when it is copied: template auto_ptr & auto_ptr ::operator=(auto_ptr & rhs) { if (this != &rhs) { delete ptr; ptr = rhs.ptr; rhs.ptr = NULL; } return *this; }

Benefits of Smart Pointers The main, obvious benefits of using smart pointers as stated before are the increased efficiency of memory management over normal pointers. This efficiency consists of three main abilities of smart pointers which are, automated initialisation, handling of dangling pointers and automatic clean up.

Automated initialisation removes the need for setting the smart pointer to NULL, which therefore removes the need for that code to be written, which is similar to the benefits of automatic clean up in a way. Benefits of Smart Pointers The automatic clean up feature means that smart pointers automatically clean up, reduces the amount of code needed to be written, and in turn reducing the possibility of bugs.

Benefits of Smart Pointers Major benefit of the smart pointer is its handling of dangling pointers. These so called dangling pointers are a very common problem and are caused by the pointer pointing to an object that is already deleted. Another problem faced by software programmers is the possibility of an exception error occurring in the program.

Benefits of Smart Pointers If an exception occurs within a pointer this means that the remaining code after it will not get executed and in turn the pointer will not get deleted with the potential of memory leaks occurring. However the use of a smart pointer will remove this threat due to the automatic clean up of the pointer because the pointer will be cleaned up whenever it gets out of scope, whether it was during the normal path of execution or during an exception. This solution is possible to write for normal pointers; however it is much simpler to implement using smart pointers

Conclusion As previously stated smart pointers are great for efficient memory management. They can be used to make more efficient use of available memory and to shorten allocation and deallocation time and prevents bugs caused by standard pointers. Auto_ptr: the simplest smart pointer to use. For situations when there are no special requirements.

The End