Smart Pointers. Some slides from Internet

Size: px
Start display at page:

Download "Smart Pointers. Some slides from Internet"

Transcription

1 Smart Pointers Some slides from Internet 1

2 Part I: Concept Reference: Using C++11 s Smart Pointers, David Kieras, EECS Department, University of Michigan C++ Primer, Stanley B. Lippman, Jesee Lajoie, Barbara E. Moo 2

3 C++11 C++11 (formerly known as C++0x) is a version of the standard of the C++ programming language. It was approved by ISO on 12 August 2011, replacing C++03, superseded by C++14 on 18 August The C++17 specification reached the Draft International Standard stage in March

4 C New language features 1.1 Function return type deduction 1.2 Alternate type deduction on declaration 1.3 Relaxed constexpr restrictions 1.4 Variable templates 1.5 Aggregate member initialization 1.6 Binary literals 1.7 Generic lambdas 1.8 Lambda captures expressions 2 New standard library features 2.1 Shared mutexes and locking 2.2 Heterogeneous lookup in associative containers 2.3 Standard user-defined literals 2.4 Tuple addressing via type 2.5 Smaller library features 4

5 Memory Management One of the major issues in writing C/C++ code is managing dynamically allocated memory Biggest question is how to ensure that allocated memory will be freed when it is no longer in use 5

6 The rule of three If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them. -is-the-rule-of-three 6

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

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

9 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. 9

10 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. 10

11 Example: String class class String { public: String( char const *str ) { int l = strlen(str); m_data = new char[l]; memcpy(m_data, str, l); } ~String() { delete [] m_data; } private: char* m_data; }; The memory for char* represented by String is owned by the object Class encapsulates details of memory management With careful implementation, this class is memory-tight 11

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

13 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. 13

14 An Example of Smart Pointers template <class T> 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;} }; 14

15 An Example of Smart Pointers Therefore instead of writing Therefore user writes void foo() { MyClass* p(new MyClass); p->dosomething(); delete p; } void foo() { auto_ptr<myclass> p(new MyClass); p->dosomething(); } 15

16 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(); p = NULL; q->dosomething(); // Watch out! p is now dangling! // p is no longer dangling // Ouch! q is still dangling! 16

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

18 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. 18

19 Benefits of Smart Pointers (2) 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. 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. 19

20 Benefits of Smart Pointers (3) 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. 20

21 Benefits of Smart Pointers (4) 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 21

22 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. 22

23 Part II: C++ 11 Smart Pointer 23

24 C++ Memory Management Idioms Idioms are reusable design techniques in a language We ll look at 4 important ones in C++ Copy constructor trick for assignment Ensures release of existing resource and acquisition of the new resource both succeed or fail together RAII (a.k.a. Guard) ties dynamic resources to other (esp. automatic) scopes Reference counting ties dynamic lifetime to a group of references Copy-on-write allows more efficient management of multiple aliasing 24

25 Copy Constructor Trick for Assignment Cleanup/assignment succeed or fail together class Array { public: Array(unsigned int) ; Array(const Array &); // assume copy constructor makes a deep copy ~Array(); Array & operator=(const Array &a); private: }; int * ints_; size_t size_; Array & Array::operator=(const Array &a) { if (&a!= this) { } Array temp(a); std::swap(temp.ints_, ints_); std::swap(temp.size_, size_); return *this; } 25

26 C++11 Smart Pointers C++11 deprecates an older smart pointer template auto_ptr : can guard dynamically allocated memory and pass ownership around, but doesn t work with the STL containers and has other limitations C++11 provides 3 new smart pointer templates instead shared_ptr : a general purpose reference counted guard for dynamic memory (we ll mostly use this one in this course) weak_ptr : gives access to a resource that is guarded by a shared_ptr without increasing reference count (can be used to prevent memory leaks due to circular references) unique_ptr : a more complex but potentially very efficient way to transfer ownership of dynamic memory safely (implements C++11 move semantics ) 26

27 Resource Acquisition Is Initialization (RAII) Also referred to as the Guard Idiom However, the term RAII is more widely used in C++ Relies on the fact that in C++ a stack object s destructor is called when stack frame pops Idea: we can use a stack object to hold the ownership of a heap object, or any other resource that requires explicit clean up Initialize stack object when the resource is allocated De-allocate resource in the stack object s destructor 27

28 RAII Example: Guarding Newly Allocated Object shared_ptr<foo> createandinit() { Foo *f = new Foo; shared_ptr<foo> p(f); init(f);// may throw exception return p; } int run () { try { shared_ptr<foo> spf = createandinit(); cout << *spf is << *spf; } catch (...) { return -1 } return 0; } RAII idiom example via shared_ptr class template #include <memory> using namespace std; shared_ptr<x> assumes and maintains ownership of aliased X Can access the aliased X through it (*spf) shared_ptr destructor calls delete on the pointer to the owned X when it s safe to do so (per reference counting idiom discussed next) Combines well with other memory idioms 28

29 reference reference reference Introduction to Reference Counting Resource counter == 3 Basic Problem Resource sharing is often more efficient than copying But it s hard to tell when all are done using a resource Must avoid early deletion Must avoid leaks Solution Approach Share both the resource and also a counter Each new reference increments the counter When a reference is done, it decrements the counter When count drops to zero, delete resource and counter last one out shuts off the lights 29

30 Reference Counting Example: Sharing an Object shared_ptr<foo> createandinit() { Foo *f = new Foo; shared_ptr<foo> p(f); init(f);// may throw exception return p; } int run () { try { shared_ptr<foo> spf = createandinit(); shared_ptr<foo> spf2 = spf; // object destroyed after // both spf and spf2 go away } catch (...) { return -1 } return 0; } RAII idiom example via shared_ptr class template #include <memory> using namespace std; shared_ptr<x> assumes ownership of aliased X shared_ptr<x> copy constructor increases count, and its destructor decreases count shared_ptr destructor calls delete on the pointer to the owned X when count drops to 0 30

31 Introduction to Copy on Write (Clone on Write) write() reference Resource 2 counter == 1 Basic Problem Reference counting enables safe and efficient sharing But what if modifications are made to the resource? May want logically separate copies of resource reference reference Resource counter == 2 Solution Start with reference counting Writer checks for count > 1 Copies reference & counter Updates both counters Performs the write Readers all share a copy, each writer can get its own 31

32 Reference Counting Suppose String has operator[] Consider the following code String a = foo bar ; String b = a; String c = a; c[2] = l ; What does this code do? 32

33 Reference Counting After we modify c, it is no longer identical to a and b We can no longer save memory by storing all three strings in one place Solution Clone on Write make a copy of an object when it is modified 33

34 Implementing operator[] in String Read-only access: char const& operator[](int i) const { return m_ptr->m_data[i]; } Read/Write access: char & operator[](int i) { } if( m_ptr->m_rc > 1 ) { // make a new copy of the string } m_ptr->m_rc--; m_ptr = new StringValue( *m_ptr ); return m_ptr->m_data[i]; 34

35 Clone on Write Perform the copy operation only when new copy is needed This is an instance of lazy evaluation How can we perform this in a generic RCPointer? 35

36 Template Clone on Write Distinguish between read only access: T const& RCPointer<T>::operator*() const; T const* RCPointer<T>::operator->() const; and read/write access T& RCPointer<T>::operator*(); T* RCPointer<T>::operator->(); In these operations we perform copy 36

37 Reference counting and cycles Reference counting could have been used as an automatic garbage collection in C++. Problem: Data structures can include cycles. In this case the pointers will never be deleted. If all these pointers were reference counted, then no memory would be freed 37

38 Weak_ptr "weak" smart pointers: these only "observe" an object but do not influence its lifetime. A ring of objects can point to each other with weak_ptrs, which point to the managed object but do not keep it in existence. the "observing" relations are shown by the dotted arrows. 38

39 How they works 39

40 How shared_ptr & weak_ptr works Whenever a shared_ptr is destroyed, or reassigned to point to a different object, the shared_ptr destructor or assignment operator decrements the shared count. Similarly, destroying or reassigning a weak_ptr will decrement the weak count. when the shared count reaches zero, the shared_ptr destructor deletes the managed object and sets the pointer to 0. If the weak count is also zero, then the manager object is deleted also, and nothing remains. 40

41 Summary: Memory Management Tips Know what goes where in memory Understand mechanics of stack and heap allocation Watch for simple (and complex) lifetime errors Think about shallow copy vs. deep copy (problems and performance trade-offs) Master useful idioms for C++ memory management Learn how they work Understand when to apply them Look for ways to apply them in the labs and beyond C++11 smart pointers (especially shared_ptr) very helpful 41

42 The End n Using C++11 s Smart Pointers, David Kieras, EECS Department, University of Michigan n C++ Primer, Stanley B. Lippman, Jesee Lajoie, Barbara E. Moo 42

Pointers. Developed By Ms. K.M.Sanghavi

Pointers. Developed By Ms. K.M.Sanghavi 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

More information

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

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers Review from Lecture 23 Basic exception mechanisms: try/throw/catch Functions & exceptions, constructors & exceptions Today

More information

Smart Pointers - What, Why, Which?

Smart Pointers - What, Why, Which? Page 1 of 7 Smart Pointers - What, Why, Which? Yonat Sharon What are they? Why would I use them? Less bugs Exception Safety Garbage collection Efficiency STL containers Which one should I use? Local variables

More information

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

CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers Announcements Please fill out your course evaluations! Those of you interested in becoming an undergraduate mentor for

More information

ALL ABOUT POINTERS C/C++ POINTERS

ALL ABOUT POINTERS C/C++ POINTERS ALL ABOUT POINTERS CS 403: Pointers, References, and Management Stefan D. Bruda Fall 2017 http://xkcd.com/138/ CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 1 / 27 POINTERS C/C++

More information

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

Project. C++: Smart Pointers. The Plan. Announcement. Memory Leak. Pointer Ownership. Today: STL 1 Wednesday: STL 2 Thursday: Smart Pointers 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

More information

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini bertini@dsi.unifi.it http://www.dsi.unifi.it/~bertini/ Resource Management Memory, auto_ptr and RAII The most commonly used resource in

More information

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

CSCI-1200 Data Structures Spring 2018 Lecture 25 Garbage Collection & Smart Pointers CSCI-1200 Data Structures Spring 2018 Lecture 25 Garbage Collection & Smart Pointers Announcements Please fill out your course evaluations! Those of you interested in becoming an undergraduate mentor for

More information

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

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak Memory Leak C++ Memory Problems or When Good Memory Goes Bad 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

More information

RAII and Smart Pointers. Ali Malik

RAII and Smart Pointers. Ali Malik 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

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

Homework 4. Any questions?

Homework 4. Any questions? CSE333 SECTION 8 Homework 4 Any questions? STL Standard Template Library Has many pre-build container classes STL containers store by value, not by reference Should try to use this as much as possible

More information

G52CPP C++ Programming Lecture 20

G52CPP C++ Programming Lecture 20 G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not

More information

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

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011 More C++ David Chisnall March 17, 2011 Exceptions A more fashionable goto Provides a second way of sending an error condition up the stack until it can be handled Lets intervening stack frames ignore errors

More information

Assertions and Exceptions

Assertions and Exceptions CS 247: Software Engineering Principles Assertions and Exceptions Reading: Eckel, Vol. 2 Ch. 1 Exception Handling U Waterloo CS247 (Spring 2017) p.1/32 Defensive Programming The question isn t whether

More information

Chapter 13: Copy Control. Overview. Overview. Overview

Chapter 13: Copy Control. Overview. Overview. Overview Chapter 13: Copy Control Overview The Copy Constructor The Assignment Operator The Destructor A Message-Handling Example Managing Pointer Members Each type, whether a built-in or class type, defines the

More information

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

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 14 -- smart pointers Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New exercise out today, due Wednesday morning Exam Friday

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 14 -- smart pointers Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia Midterm Friday - Review in sections this week - Closed book; topic list

More information

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

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Using pointers Pointers are polymorphic Pointer this Using const with pointers Stack and Heap Memory leaks and dangling pointers

More information

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Resource Management Memory, smart pointers and RAII Resource management The most

More information

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Resource Management Memory, smart pointers and RAII Resource management The most

More information

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

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

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

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

Midterm Review. PIC 10B Spring 2018

Midterm Review. PIC 10B Spring 2018 Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed

More information

C++ is Evolving. std::array

C++ is Evolving. std::array C++ is Evolving C++ is an evolving language. A committee of the ISO (International Organization for Standards) ratifies proposed changes to C++. New standards have been released every few years. In this

More information

Objects Managing a Resource

Objects Managing a Resource Objects Managing a Resource 1 What is a Resource Respects Release/Acquire protocol files (open/close) memory allocation (allocate/free) locks (acquire/release). 2 What is a Resource Objects when constructed,

More information

Engineering Robust Server Software

Engineering Robust Server Software Engineering Robust Server Software Exceptions Exceptions Handling problems: exceptions C++ Java temp-and-swap RAII Smart Pointers finally specifications finalizers (and why they are not what you need for

More information

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

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103

More information

04-17 Discussion Notes

04-17 Discussion Notes 04-17 Discussion Notes PIC 10B Spring 2018 1 RAII RAII is an acronym for the idiom Resource Acquisition is Initialization. What is meant by resource acquisition is initialization is that a resource should

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Smart Pointers and Constness Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer

More information

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

Copy Control 2008/04/08. Programming Research Laboratory Seoul National University Copy Control 2008/04/08 Soonho Kong soon@ropas.snu.ac.kr Programming Research Laboratory Seoul National University 1 Most of text and examples are excerpted from C++ Primer 4 th e/d. 2 Types control what

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

Vector and Free Store (Vectors and Arrays)

Vector and Free Store (Vectors and Arrays) DM560 Introduction to Programming in C++ Vector and Free Store (Vectors and Arrays) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides by Bjarne

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 13 -- smart pointers Steve Gribble Department of Computer Science & Engineering University of Washington Administrivia HW2 is due on Thursday! - check out the discussion board for a few

More information

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

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington CSE 333 Lecture 11 - constructor insanity Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia Exercises: - New exercise out today, due Monday morning

More information

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8

More information

In Java we have the keyword null, which is the value of an uninitialized reference type

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

Pointers! Arizona State University 1

Pointers! Arizona State University 1 Pointers! CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 10 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

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

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I Polynomial Class Polynomial(); Polynomial(const string& N, const vector& C); Polynomial operator+(const Polynomial& RHS) const; Polynomial operator-(const Polynomial& RHS) const; Polynomial operator*(const

More information

CA341 - Comparative Programming Languages

CA341 - Comparative Programming Languages CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data

More information

6 Architecture of C++ programs

6 Architecture of C++ programs 6 Architecture of C++ programs 1 Preview managing memory and other resources "resource acquisition is initialization" (RAII) using std::auto_ptr and other smart pointers safe construction of an object

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract

More information

Consider the program...

Consider the program... Smart Pointers Consider the program... When the scope of foo is entered storage for pointer x is created The new allocates storage on the heap class X {... When the scope foo is left, the storage for x

More information

Financial computing with C++

Financial computing with C++ Financial Computing with C++, Lecture 6 - p1/24 Financial computing with C++ LG Gyurkó University of Oxford Michaelmas Term 2015 Financial Computing with C++, Lecture 6 - p2/24 Outline Linked lists Linked

More information

A Generic Non-intrusive Smart Pointer Implementation

A Generic Non-intrusive Smart Pointer Implementation A Generic Non-intrusive Smart Pointer Implementation Anthony Williams 13th March 2001 1 Background I started writing an article about resource management using Resource Acquisition Is Initialisation (RAII),

More information

C++11 and Compiler Update

C++11 and Compiler Update C++11 and Compiler Update John JT Thomas Sr. Director Application Developer Products About this Session A Brief History Features of C++11 you should be using now Questions 2 Bjarne Stroustrup C with Objects

More information

CS 241 Honors Memory

CS 241 Honors Memory CS 241 Honors Memory Ben Kurtovic Atul Sandur Bhuvan Venkatesh Brian Zhou Kevin Hong University of Illinois Urbana Champaign February 20, 2018 CS 241 Course Staff (UIUC) Memory February 20, 2018 1 / 35

More information

Programmazione. Prof. Marco Bertini

Programmazione. Prof. Marco Bertini Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Resource Management Memory, smart pointers and RAII Resource management The most commonly used resource in C++

More information

Vector and Free Store (Pointers and Memory Allocation)

Vector and Free Store (Pointers and Memory Allocation) DM560 Introduction to Programming in C++ Vector and Free Store (Pointers and Memory Allocation) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides

More information

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

Advanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const. The user. Advanced C++ For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 #define private public #define protected public #define class struct Source: Lutz

More information

G52CPP C++ Programming Lecture 16

G52CPP C++ Programming Lecture 16 G52CPP C++ Programming Lecture 16 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Casting static cast dynamic cast const cast reinterpret cast Implicit type conversion 2 How

More information

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS Pages 792 to 800 Anna Rakitianskaia, University of Pretoria INITIALISING POINTER VARIABLES Pointer variables are declared by putting

More information

Cute C++ idioms Nikhil Marathe.

Cute C++ idioms Nikhil Marathe. Cute C++ idioms Nikhil Marathe http://nikhilism.com Everybody knows 10% of C++ Qt style No exceptions Return values indicate errors Well defined memory models Qt tree based ownership, occasional ref counting

More information

04-19 Discussion Notes

04-19 Discussion Notes 04-19 Discussion Notes PIC 10B Spring 2018 1 Constructors and Destructors 1.1 Copy Constructor The copy constructor should copy data. However, it s not this simple, and we need to make a distinction here

More information

Lecture 15a Persistent Memory & Shared Pointers

Lecture 15a Persistent Memory & Shared Pointers Lecture 15a Persistent Memory & Shared Pointers Dec. 5 th, 2017 Jack Applin, Guest Lecturer 2017-12-04 CS253 Fall 2017 Jack Applin & Bruce Draper 1 Announcements PA9 is due today Recitation : extra help

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.... COMP6771 Advanced C++ Programming Week 5 Part One: Exception Handling 2016 www.cse.unsw.edu.au/ cs6771 2.... Memory Management & Exception Handling.1 Part I: Exception Handling Exception objects

More information

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

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC CSCI 262 Data Structures 9 Dynamically Allocated Memory POINTERS AND ARRAYS 2 Arrays Arrays are just sequential chunks of memory: Arrays and Pointers Array variables are secretly pointers: x19 x18 x17

More information

GEA 2017, Week 4. February 21, 2017

GEA 2017, Week 4. February 21, 2017 GEA 2017, Week 4 February 21, 2017 1. Problem 1 After debugging the program through GDB, we can see that an allocated memory buffer has been freed twice. At the time foo(...) gets called in the main function,

More information

Introducing C++ to Java Programmers

Introducing C++ to Java Programmers Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:

More information

Pointers and References

Pointers and References Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers

More information

Pointers and Memory 1

Pointers and Memory 1 Pointers and Memory 1 Pointer values Pointer values are memory addresses Think of them as a kind of integer values The first byte of memory is 0, the next 1, and so on A pointer p can hold the address

More information

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

Exception Safety. CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, Glenn G. Chappell. continued continued CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions

More information

CS24 Week 3 Lecture 1

CS24 Week 3 Lecture 1 CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation

More information

C++ Programming Lecture 7 Software Engineering Group

C++ Programming Lecture 7 Software Engineering Group C++ Programming Lecture 7 Software Engineering Group Philipp D. Schubert Contents 1. Template metaprogramming 2. Variadic template arguments 3. Smart pointer Template metaprogramming Template metaprogramming

More information

Smart Pointers in C++11

Smart Pointers in C++11 Smart Pointers in C++11 Karl Stratos 1 Background 1.1 Pointers When we write T x to create an instance x of type T, we allocate the amount of memory required for T and names it as x. We can reference (i.e.,

More information

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

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Proposed Wording for Concurrent Data Structures: Hazard Pointer and Read Copy Update (RCU)

Proposed Wording for Concurrent Data Structures: Hazard Pointer and Read Copy Update (RCU) Document number: D0566R1 Date: 20170619 (pre Toronto) Project: Programming Language C++, WG21, SG1,SG14, LEWG, LWG Authors: Michael Wong, Maged M. Michael, Paul McKenney, Geoffrey Romer, Andrew Hunter

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

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

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms Introduction to Linked Lists Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms Lecture Slides Friday, September 25, 2009 Glenn G. Chappell Department of Computer Science

More information

CS 101: Computer Programming and Utilization

CS 101: Computer Programming and Utilization CS 101: Computer Programming and Utilization Jul-Nov 2017 Umesh Bellur (cs101@cse.iitb.ac.in) Lecture 16: Representing variable length entities (introducing new and delete) A programming problem Design

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

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

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

More information

Memory management COSC346

Memory management COSC346 Memory management COSC346 Life cycle of an object Create a reference pointer Allocate memory for the object Initialise internal data Do stuff Destroy the object Release memory 2 Constructors and destructors

More information

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation Announcements Lab 3 was a Frankenstein assembly of a new group exercise with part of a gdb lab. I hear many of you

More information

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

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

Assignment 1: SmartPointer

Assignment 1: SmartPointer CS106L Winter 2007-2008 Handout #19 Wednesday, February 27 Assignment 1: SmartPointer Due Monday, March 10, 11:59 PM Introduction Several lectures ago we discussed the auto_ptr class, an object that mimics

More information

Chapter 17 vector and Free Store. Bjarne Stroustrup

Chapter 17 vector and Free Store. Bjarne Stroustrup Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:

More information

Using C++11 s Smart Pointers

Using C++11 s Smart Pointers Using C++11 s Smart Pointers David Kieras, EECS Department, University of Michigan May 2015 This tutorial deals with C++11's smart pointer facility, which consists unique_ptr, shared_ptr and its partner,

More information

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

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction CS106L Spring 2009 Handout #21 May 12, 2009 static Introduction Most of the time, you'll design classes so that any two instances of that class are independent. That is, if you have two objects one and

More information

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

CA31-1K DIS. Pointers. TA: You Lu CA31-1K DIS Pointers TA: You Lu Pointers Recall that while we think of variables by their names like: int numbers; Computer likes to think of variables by their memory address: 0012FED4 A pointer is a

More information

G52CPP C++ Programming Lecture 17

G52CPP C++ Programming Lecture 17 G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions

More information

C++ Primer for CS175

C++ Primer for CS175 C++ Primer for CS175 Yuanchen Zhu September 10, 2014 This primer is pretty long and might scare you. Don t worry! To do the assignments you don t need to understand every point made here. However this

More information

C++ Primer, Fifth Edition

C++ Primer, Fifth Edition C++ Primer, Fifth Edition Stanley B. Lippman Josée Lajoie Barbara E. Moo Upper Saddle River, NJ Boston Indianapolis San Francisco New York Toronto Montreal London Munich Paris Madrid Capetown Sidney Tokyo

More information

CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages CSE 307: Principles of Programming Languages Variables and Constants R. Sekar 1 / 22 Topics 2 / 22 Variables and Constants Variables are stored in memory, whereas constants need not be. Value of variables

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example

More information

STL Quick Reference for CS 241

STL Quick Reference for CS 241 STL Quick Reference for CS 241 Spring 2018 The purpose of this document is to provide basic information on those elements of the C++14 standard library we think are most likely to be needed in CS 241.

More information

05-01 Discussion Notes

05-01 Discussion Notes 05-01 Discussion Notes PIC 10B Spring 2018 1 Exceptions 1.1 Introduction Exceptions are used to signify that a function is being used incorrectly. Once an exception is thrown, it is up to the programmer

More information

It turns out that races can be eliminated without sacrificing much in terms of performance or expressive power.

It turns out that races can be eliminated without sacrificing much in terms of performance or expressive power. The biggest two problems in multi-threaded programming are races and deadlocks. Races reached new levels with the introduction of relaxed memory processors. It turns out that races can be eliminated without

More information

Exercise 6.2 A generic container class

Exercise 6.2 A generic container class Exercise 6.2 A generic container class The goal of this exercise is to write a class Array that mimics the behavior of a C++ array, but provides more intelligent memory management a) Start with the input

More information

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

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo Chapter 10 Pointers and Dynamic Arrays 1 Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic Classes, Pointers, Dynamic Arrays The this

More information

Written by John Bell for CS 342, Spring 2018

Written by John Bell for CS 342, Spring 2018 Advanced OO Concepts Written by John Bell for CS 342, Spring 2018 Based on chapter 3 of The Object-Oriented Thought Process by Matt Weisfeld, with additional material from other sources. Constructors Constructors

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 10 Pointers and Dynamic Arrays Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic

More information

Implementing Abstractions

Implementing Abstractions Implementing Abstractions Pointers A pointer is a C++ variable that stores the address of an object. Given a pointer to an object, we can get back the original object. Can then read the object's value.

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main

More information