The Standard Template Library – part 2. auto_ptr<> Regular pointers may cause memory leaks Regular pointers may cause memory leaks void f() { SomeClass.

Slides:



Advertisements
Similar presentations
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Advertisements

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Introduction to Programming Lecture 39. Copy Constructor.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 18 Stacks.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 18: Stacks And Queues.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 18: Stacks and.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
Review of C++ Programming Part II Sheng-Fang Huang.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
1 Stacks Stack Examples Stack API More Examples/Uses Base Conversion Activation Records RPN Implementing a Stack Stacks.
Data Structures Using C++ 2E
Containers Overview and Class Vector
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Generic Positional Containers and Double-Ended Queues.
SNU OOPSLA Lab. Chap17. Standard Containers © copyright 2001 SNU OOPSLA Lab.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Generic Programming Using the C++ Standard Template Library.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
C++ STL CSCI 3110.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 18 Stacks and Queues.
Pointers OVERVIEW.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
1 Recall Definition of Stack l Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and addition of.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 18: Stacks and Queues.
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
A gentle introduction to the standard template library (STL) Some references:
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
1 Queues Queue API Application: Radix Sort Implementation: Using Deque Using Deque Circular Array Circular Array Priority Queue Priority Queue API Implementation.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 20: Container classes; strings.
1 Linked Lists Assignment What about assignment? –Suppose you have linked lists: List lst1, lst2; lst1.push_front( 35 ); lst1.push_front( 18 ); lst2.push_front(
PROGRAMMING 1 – HELPER INSTRUCTIONS ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1.
CSCI-383 Object-Oriented Programming & Design Lecture 30.
Copyright © Curt Hill STL Priority Queue A Heap-Like Adaptor Class.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
1 Generic Positional Containers and Double-Ended Queues.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 18: Stacks and Queues.
Pointers and Dynamic Arrays
18 Chapter Stacks and Queues
Chapter 18: Stacks and Queues.
Introduction to Computers Computer Generations
Standard Template Library (STL)
Pointers and Linked Lists
Basic Data Structures.
Chapter 19: Stacks and Queues.
CISC/CMPE320 - Prof. McLeod
C++ STL Stack, Queue, and Deque
Chapter 9: Pointers and String
Dynamic allocation (continued)
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Presentation transcript:

The Standard Template Library – part 2

auto_ptr<> Regular pointers may cause memory leaks Regular pointers may cause memory leaks void f() { SomeClass *ptr = new SomeClass; SomeClass *ptr = new SomeClass; … // exception or improperly implemented early return from f() // exception or improperly implemented early return from f() … delete ptr; // memory leak if this statement is not reached delete ptr; // memory leak if this statement is not reached} The memory leak may be avoided The memory leak may be avoided We may use exception mechanism to catch exceptions We may use exception mechanism to catch exceptions We shoud delete all allocated memory in case of early return We shoud delete all allocated memory in case of early return

auto_ptr<> auto_ptr is an object (template) that auto_ptr is an object (template) that Acts as an inteligent pointer Acts as an inteligent pointer Owns data assigned to it Owns data assigned to it Manages asigned data to avoid memory leaks Manages asigned data to avoid memory leaks (defined in header) (defined in header) void f() { std::auto_ptr ptr(SomeClass); std::auto_ptr ptr(SomeClass); … // exception or early return from f() – ok! // exception or early return from f() – ok! … // no need to delete ptr; ~auto_ptr() does it for us // no need to delete ptr; ~auto_ptr() does it for us}

auto_ptr<> auto_ptr owns data assigned to it auto_ptr owns data assigned to it Assignment from regular pointer not allowed Assignment from regular pointer not allowed // std::auto_ptr ptr = new SomeClass; ERROR, but there is a reset() There may be only one one auto_ptr that owns specific object/variable There may be only one one auto_ptr that owns specific object/variable copy constructor and assignment operator move data from source auto_ptr, so they modify their arguments – unusual behaviour copy constructor and assignment operator move data from source auto_ptr, so they modify their arguments – unusual behaviour auto_ptr should not be an element of a container (why?) auto_ptr should not be an element of a container (why?) auto_ptr acts as an inteligent pointer auto_ptr acts as an inteligent pointer Overloads *(ptr) and ptr-> Overloads *(ptr) and ptr-> It is a pointer to single object, not to an array, container – ok. It is a pointer to single object, not to an array, container – ok. Does not overload pointer arithmetic operators (++, [], etc) Does not overload pointer arithmetic operators (++, [], etc) Extra methods : Extra methods : T* get() – returns address of the owned data (or NULL), not changing ownership T* get() – returns address of the owned data (or NULL), not changing ownership T* release() – returns address of the owned data (or NULL), releasing ownership T* release() – returns address of the owned data (or NULL), releasing ownership void reset(T * ptr=0) – assignment from regular pointer, creating ownership void reset(T * ptr=0) – assignment from regular pointer, creating ownership

auto_ptr<> copy constructor copy constructor std::auto_ptr ptr1(SomeClass); std::auto_ptr ptr2(ptr1); // now ptr1 is empty assignment operator assignment operator std::auto_ptr ptr1(SomeClass); std::auto_ptr ptr2(SomeClass); ptr2=ptr1; // *ptr2 (old one) gets destructed first, // now ptr1 is empty

auto_ptr<> auto_ptr as argument or return value auto_ptr as argument or return value Should be passed as variable, not as reference Should be passed as variable, not as reference This way we create sink (argument) or source (ret. val.) of data This way we create sink (argument) or source (ret. val.) of data const auto_ptr const auto_ptr will not allow to transfer owned data to another auto_ptr will not allow to transfer owned data to another auto_ptr will not allow to assign data owned by another auto_ptr will not allow to assign data owned by another auto_ptr ultimately will destruct owned data ultimately will destruct owned data changing owned data still ok. changing owned data still ok. good for sink good for sink const auto_ptr & const auto_ptr & for functions operating on owned data without changing ownership for functions operating on owned data without changing ownership examples: util/autoptr1.cpp util/autoptr2.cpp examples: util/autoptr1.cpp util/autoptr2.cpp

auto_ptr<> auto_ptr as a member variable auto_ptr as a member variable may make destructor not necessary may make destructor not necessary is safe even for exceptions thrown by a constructor is safe even for exceptions thrown by a constructor as opposed to regular pointers, since if constructor fails then destructor is not executed as opposed to regular pointers, since if constructor fails then destructor is not executed usually requires implementing copy constructor and assignment operator usually requires implementing copy constructor and assignment operator since default ones woud remove data from object being assigned since default ones woud remove data from object being assigned

numeric_limits<> numeric_limits<> is a template that defines various properties of a numerical types numeric_limits<> is a template that defines various properties of a numerical types member variables and methods should be used to determine type properties at the compile time member variables and methods should be used to determine type properties at the compile time numeric_limits ::digits // no. of bits for integer types numeric_limits ::digits // no. of bits for integer types numeric_limits ::max() // easy to guess numeric_limits ::max() // easy to guess … it is implemented as a template that has specializations for all fundamental types it is implemented as a template that has specializations for all fundamental types

Special containers stack (LIFO queue, implemented using deque) stack (LIFO queue, implemented using deque) queue (FIFO queue, implemented using deque) queue (FIFO queue, implemented using deque) priority_queue priority_queue bitset bitset hash_set, hash_multiset, hash_map, hash_multimap hash_set, hash_multiset, hash_map, hash_multimap (implemented using hash table instead of binary tree)

stack header header simple LIFO queue implemented using deque simple LIFO queue implemented using deque may be based on any container supporting: back(), push_back(), pop_back(), may be based on any container supporting: back(), push_back(), pop_back(), just give 2 nd template argument, eg.: stack > just give 2 nd template argument, eg.: stack > just redirects own methods to deque methods to obtain LIFO queue just redirects own methods to deque methods to obtain LIFO queue example: cont/stack1.cpp example: cont/stack1.cpp push() push() pop() pop() top() // get the value of topmost element // but do not remove it from stack top() // get the value of topmost element // but do not remove it from stack size()// get the current number of elemets size()// get the current number of elemets empty()// is it empty empty()// is it empty operators: ==, !=,, =// == returns 1 if size and all elements are equal operators: ==, !=,, =// == returns 1 if size and all elements are equal no more methods or operators no more methods or operators

queue header header simple FIFO queue implemented using deque simple FIFO queue implemented using deque may be based on any container supporting: front(), back(), push_back(), pop_front() may be based on any container supporting: front(), back(), push_back(), pop_front() just give 2 nd template argument, eg.: queue > just give 2 nd template argument, eg.: queue > just redirects own methods to deque methods to obtain FIFO queue just redirects own methods to deque methods to obtain FIFO queue example: cont/queue1.cpp example: cont/queue1.cpp push() push() pop() pop() back() // get the value of element most recently push-ed // but do not remove it from stack back() // get the value of element most recently push-ed // but do not remove it from stack front() // get the value of element at the front of queue // but do not remove it from queue front() // get the value of element at the front of queue // but do not remove it from queue size()// get the current number of elemets size()// get the current number of elemets empty()// is it empty empty()// is it empty operators: ==, !=,, =// == returns 1 if size and all elements are equal operators: ==, !=,, =// == returns 1 if size and all elements are equal no more methods or operators no more methods or operators

priority_queue header header simple priority queue implemented using vector simple priority queue implemented using vector may be based on any container supporting: front(), push_back(), pop_front(), oper.[] may be based on any container supporting: front(), push_back(), pop_front(), oper.[] just give 2 nd template argument, eg.: priority_queue > just give 2 nd template argument, eg.: priority_queue > the 3 rd argument is a sort criterion (defaults to operator< ) the 3 rd argument is a sort criterion (defaults to operator< ) priority_queue, greater > redirects own methods to vector methods redirects own methods to vector methods example: cont/pqueue1.cpp example: cont/pqueue1.cpp push() push() pop() pop() top() // get the value of element of the greatest priority // but do not remove it from queue top() // get the value of element of the greatest priority // but do not remove it from queue size()// get the current number of elemets size()// get the current number of elemets empty()// is it empty empty()// is it empty no more methods or operators (no operator ==, etc.) no more methods or operators (no operator ==, etc.)

bitset header header convinient class for handling fixed size sets of bits convinient class for handling fixed size sets of bits bitset flags; performing bit stream i/o performing bit stream i/o example: cont/bitset1.cpp example: cont/bitset1.cpp also to perform integer i/o in binary format also to perform integer i/o in binary format example: cont/bitset2.cpp example: cont/bitset2.cpp no copy constructor or assignment operator no copy constructor or assignment operator

bitset bitset constructors bitset constructorsbitset<bits>::bitset() bitset ::bitset(unsigned long val) bitset ::bitset(const string &sc) // no char* initialization, couple variants of string initialization bitset methods and operators bitset methods and operators size() // return size of bitset count() // count ones any() // 1 if at least one bit set none() // !any() test(size_t idx) // is the idx-th bit set operator==(const bitset & arg) operator!=(const bitset & arg) …

bitset bitset methods and operators bitset methods and operators set() // set all to ones set(size_t idx, int value=1) reset() // set all to zeroes reset(size_t idx)// set idx-th to zeroes flip() // negate all bits flip(size_t idx) bitwise operators (argument size must match): ^= |= &= ^ | & ~ bitwise shift operators (size_t argument): >= >> steram operators: > bool operator[] (size_t idx) const // undefined behaviour if idx out of range bitset ::reference operator[] (size_t idx) // returns object of special proxy type // with reference type we may: =(bool), =(const reference &), flip(), operator~(), bool() to_ulong(), to_string()