Memory Management with Classes

Slides:



Advertisements
Similar presentations
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.
Advertisements

Introduction to Programming Lecture 39. Copy Constructor.
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.
CSE 332: C++ copy control I Copy Control (Part I) Copy control consists of 5 distinct operations –A copy constructor initializes an object by duplicating.
Winter 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assn 4 posted shortly. Demonstrate a memory leak problem using the assignment 4 solution. Back to.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Dynamically Allocated Arrays May 2, Quiz 5 Today.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
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.
Implications of Inheritance COMP204, Bernhard Pfahringer.
C++ Memory Overview 4 major memory segments Key differences from Java
Dynamically Allocated Arrays December 4, Skip the Rest of this PowerPoint.
Object-Oriented Programming in C++
More C++ Features True object initialisation
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:
Writing Correct C++ Programs without “delete” Huang-Ming Huang CSE332 Guest Lecture Washington University in St. Louis.
CSE 332: Memory management with C++ classes Memory Management with Classes Review: for non-static built-in (native) types –default constructor and destructor.
On dynamic memory and classes ● We previously had only discussed dynamic memory in regards to structs and dynamic arrays. ● However, they can be used (to.
Memory Management.
C11, Implications of Inheritance
Motivation for Generic Programming in C++
Constructors and Destructors
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Pointers and Dynamic Arrays
Learning Objectives Pointers as dada members
Overview 4 major memory segments Key differences from Java stack
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Motivation and Overview
Andy Wang Object Oriented Programming in C++ COP 3330
C++ Object-Oriented Programming
Introduction to Classes
C++ Memory Management Idioms
Pointers Revisited What is variable address, name, value?
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Memberwise Assignment / Initialization
CMSC 202 Lesson 21 Exceptions II.
Advanced Programming Behnam Hatami Fall 2017.
Dynamically Allocated Memory
Pointers and References
Dynamic Memory Allocation
CSC 253 Lecture 8.
Introduction to Classes
CSC 253 Lecture 8.
Overview 4 major memory segments Key differences from Java stack
understanding memory usage by a c++ program
Chapter 15 Pointers, Dynamic Data, and Reference Types
Overview of Memory Layout in C++
Exceptions 2 CMSC 202.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers And Memory Acknowledgement: THE Slides are Prepared FROM SLIDES PROVIDED By NANCY M. AMATO AND Jory Denny.
Constructors and Destructors
CISC/CMPE320 - Prof. McLeod
Pointers and Arrays Beyond Chapter 16
Destructor CSCE 121 J. Michael Moore.
Class and Objects In a class, all the functions that operate on the data structure are grouped together in one place along with the data Like a struct.
Destructor CSCE 121.
COP 3330 Object-oriented Programming in C++
Class: Special Topics 2 For classes using memory allocation
Pointers and References
Pointers and References
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Destructors, Copy Constructors & Copy Assignment Operators
Rule of Three Part 1 & 2.
Destructors, Copy Constructors & Copy Assignment Operators
More C++ Classes Systems Programming.
Copy Constructors and Overloaded Assignment
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Memory Management with Classes Review: for non-static built-in (native) types default constructor and destructor do nothing copy constructor and assignment operator (re-)value member-wise Review: variables vs. the pointers and references to them may have different scopes May result in obvious kinds of lifetime errors But may also introduce more subtle issues of aliasing Can risk destroying an object too soon or too late Basic ideas in memory management with classes Constructor allocates, destructor de-allocates: an object “owns” memory Shallow copy vs. deep copy: aliasing vs. duplication

Constructor Allocates, Destructor De-allocates #ifndef INTARRAY_H #define INTARRAY_H class IntArray { public: IntArray(size_t); ~IntArray(); int & operator[](size_t); IntArray(const IntArray &); private: size_t m_size; int *m_values; }; #endif /* INTARRAY_H */ Resources allocated by an object need to be freed Constructor, destructor offer good start/end points Example: class to hold a fixed sized array Can store integer values Can access each element Array size may differ for each object Once set, object’s array size is fixed

Constructor/Destructor, continued #include “IntArray.h" IntArray::IntArray(size_t s) :m_size(s), m_values(0) { if (m_size > 0) { m_values = new int[m_size]; } IntArray::~IntArray() { delete [] m_values; int & IntArray::operator[](size_t s){ if (!m_values || s >= m_size) { throw 1; return m_values [s]; Initialization list sets m_size to the passed length, and also sets m_values to 0 Only allocate if length is greater than zero What does new do? Allocates memory Calls constructor(s) Destructor releases the allocated array via delete Calls elements’ destructors Returns memory to the heap

Constructor/Destructor, continued int main(int, char*[]) { IntArray a(6); // When a is created, it // usually allocates some // memory (here, 6 ints) return 0; // Now a is destroyed, and // since it’s destructor // is called, so is the // memory it allocated } So, scopes are tied together IntArray and its memory What does delete do? Calls destructor(s) Frees memory What are new [] and delete [] vs. new and delete? What if m_values was 0 when delete was called on it? Remember what happens?

Copy Constructor: Shallow Copy // just uses the array that’s already in the other object IntArray::IntArray(const IntArray &a) :m_size(a.m_size), m_values(a.m_values) { } There are two ways to “copy” Shallow: aliases existing resources Deep: makes a complete and separate copy Version above shows shallow copy Efficient But may be risky. Why? Hint: destructor (how to fix?) What’s the invariant established by this code? Hint: what can we say about m_size and m_values?

Copy Constructor: Deep Copy // makes its own copy of the array IntArray::IntArray(const IntArray &a) :m_size(a.m_size), m_values(0) { if (m_size > 0) { m_values = new int[m_size]; for (size_t i = 0; i < m_size; ++i) { m_values[i] = a.m_values[i]; } This code shows deep copy Safe: no shared aliasing But may not be very efficient Note trade-offs with arrays Allocate memory once More efficient than multiple calls to new (heap search) Constructor and assignment called on each array element Less efficient than block copy E.g., using memcpy() But sometimes more correct i.e., constructors and destructors are called

Also Think About When to Use “new” Objects have to live beyond current scope Is object copying a viable solution? Good for copy : Card objects Object size is small Non-polymorphic Bad for copy : Player, Game objects. Involve heap memory allocation Polymorphic Is object swapping a good alternative? Good for objects with embedded heap objects such as Player, std::string All STL containers, like std::vector, std::set, std::map, …, etc. Not useful for polymorphic classes Game* makeGame(const char* name) { Game* result = 0; if (strcmp(name,”bridge”)==0) result= new BridgeGame; else if (strcmp(name,”hearts”)==0) result= new HeartsGame; return result; }

Summary: Memory Management With Classes Know what goes where in memory Understand the mechanics of stack vs. heap allocation Watch for simple lifetime errors Think about (and sketch) more subtle scope/lifetime issues Pay attention to aliasing issues Think about shallow copy vs. deep copy (problems/trade-offs)