Copy Control and Memory Management

Similar documents
CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

CEC225 COURSE COMPACT

C++ Overloading, Constructors, Assignment operator

Memory Allocation. Static Allocation. Dynamic Allocation. Memory Management. Dynamic Allocation. Dynamic Storage Allocation

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Glossary of Object Oriented Terms

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

The C Programming Language course syllabus associate level

C++ INTERVIEW QUESTIONS

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Object Oriented Software Design II

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

13 Classes & Objects with Constructors/Destructors

C Compiler Targeting the Java Virtual Machine

How To Teach C++ Data Structure Programming

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Chapter 13 Storage classes

Java Interview Questions and Answers

Lecture 9. Semantic Analysis Scoping and Symbol Table

Classes and Pointers: Some Peculiarities (cont d.)

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Object Oriented Software Design II

CA Compiler Construction

Sources: On the Web: Slides will be available on:

Parameter Passing in Pascal

Linked List as an ADT (cont d.)

El Dorado Union High School District Educational Services

An Incomplete C++ Primer. University of Wyoming MA 5310

Advanced Data Structures

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Java (12 Weeks) Introduction to Java Programming Language

Chapter 5 Names, Bindings, Type Checking, and Scopes

BCS2B02: OOP Concepts and Data Structures Using C++

Stack Allocation. Run-Time Data Structures. Static Structures

Data Structures Using C++ 2E. Chapter 5 Linked Lists

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 20: Stack Frames 7 March 08

Variable Base Interface

The Advantages of Dan Grossman CSE303 Spring 2005, Lecture 25

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Symbol Tables. Introduction

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Object Oriented Programming With C++(10CS36) Question Bank. UNIT 1: Introduction to C++

Description of Class Mutation Mutation Operators for Java

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Node-Based Structures Linked Lists: Implementation

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

Curriculum Map. Discipline: Computer Science Course: C++

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object

Unordered Linked Lists

CSE 504: Compiler Design. Data Flow Analysis

OpenCL Static C++ Kernel Language Extension

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Monitors, Java, Threads and Processes

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

PHP Object Oriented Classes and objects

C++FA 3.1 OPTIMIZING C++

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

C++ Programming Language

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Django Assess Managed Nicely Documentation

Compile-time type versus run-time type. Consider the parameter to this function:

Application of Stacks: Postfix Expressions Calculator (cont d.)

Object-Oriented Programming Lecture 2: Classes and Objects

PART IV Performance oriented design, Performance testing, Performance tuning & Performance solutions. Outline. Performance oriented design

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

Source Code Security Analysis Tool Functional Specification Version 1.0

CIS 190: C/C++ Programming. Polymorphism

Friendship and Encapsulation in C++

C++ Crash Kurs. C++ Object-Oriented Programming

Class 16: Function Parameters and Polymorphism

Web development... the server side (of the force)

Module 2 Stacks and Queues: Abstract Data Types

explicit class and default definitions revision of SC22/WG21/N1582 = and SC22/WG21/ N

Information technology Programming languages Fortran Enhanced data type facilities

OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES CONSTRUCTORS AND DESTRUCTORS

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Checking Access to Protected Members in the Java Virtual Machine

Constructor, Destructor, Accessibility and Virtual Functions

Android Application Development Course Program

Debugging Java Applications

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Parallel and Distributed Computing Programming Assignment 1

VB.NET Programming Fundamentals

How to create/avoid memory leak in Java and.net? Venkat Subramaniam

PROGRAMMING CONCEPTS AND EMBEDDED PROGRAMMING IN C, C++ and JAVA: Lesson-4: Data Structures: Stacks

Java CPD (I) Frans Coenen Department of Computer Science

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

Applied Informatics C++ Coding Style Guide

Objected oriented Programming: C++ Unit 1 1. Introduction 1.1. Introduction to Object Oriented Programming C++ fundamentals.

Transcription:

Copy Control and Memory Management Overview Types of memory Copy constructor, assignment operator, and destructor Reference counting with smart pointers References Stanley B. Lippman, Josée Lajoie, and Barbara E. Moo: C++ Primer. 4th Edition. Addison-Wesley (2006) Bruno R. Preiss: Data Structures and Algorithms with Object-Oriented Design Patterns in C++. John Wiley & Sons, Inc. (1999) Andrew W. Appel with Jens Palsberg: Modern Compiler Implementation in Java. 2nd Edition, Cambridge University Press (2002). Alfred V. Aho, Ravi Sethi, and Jeffrey D. Ullman: Compilers - Principles, Techniques, and Tools. Addison-Wesley (1988) 246

Static Read-Write Memory C++ allows for two forms of global variables: Static non-class variables, Static class variables. Static variables are mapped to the global memory. Access to them depends on the visibility specifies. We can find a program s global memory in the socalled read-write.data segment. 247

The Keyword static The keyword static can be used to mark the linkage of a variable or function internal, retain the value of a local variable between function calls, declare a class instance variable, define a class method. 248

Read-Write Static Variables Static class variables must be initialized outside the class. 249

Static Read-Only Memory In combination with the const specifier we can also define read-only global variables or class variables: Const variables are often stored in the program s read-only.text segment. 250

Program Memory: Stack All value-based objects are stored in the program s stack. The program stack is automatically allocated and freed. References to stack locations are only valid when passed to a callee. References to stack locations cannot be returned from a function. 251

Stack Frames (C) higher addresses temporaries save registers previous frame incoming arguments stack pointer outgoing arguments arguments return address temporaries save registers arguments current frame next frame 252

Program Memory: Heap Every program maintains a heap for dynamically allocated objects. Each heap object is accessed through a pointer. Heap objects are not automatically freed when pointer variables become inaccessible (i.e., go out of scope). Memory management becomes essential in C++ to reclaim memory and to prevent the occurrences of socalled memory leaks. 253

List::dropFirst() Release memory associated with Node object on the heap. 254

The Dominion Over Objects Alias control is one of the most difficult problems to master in object-oriented programming. Aliases are the default in reference-based object models used, for example, in Java and C#. To guarantee uniqueness of value-based objects in C++, we are required to define copy constructors. 255

The Copy Constructor Whenever one defines a new type, one needs to specify implicitly or explicitly what has to happen when objects of that that type are copied, assigned, and destroyed. The copy constructor is a special member, taking just a single parameter that is a const reference to an object of the class itself. 256

SimpleString 257

SimpleString: Constructor & Destructor 258

SimpleString: The Operators 259

Implicit Copy Constructor 260

What Has Happened? Shallow copy: s2.fcharacters == s1.fcharacters Double free: delete s2.fcharacters, which was called in s2 + B. 261

We need an explicit copy constructor! 262

The Explicit Copy Constructor When a copy constructor is called, then all instance variables are uninitialized in the beginning. 263

Explicit Copy Constructor in Use 264

What Has Happened? Deep copy: s2.fcharacters!= s1.fcharacters 265

That s it. No more problems, or? 266

A Simple Assignment 267

What Has Happened? Shallow copy: s2.fcharacters == s1.fcharacters Double free: delete s2.fcharacters, which is the same as s1.fcharacters. 268

Rule Of Thumb Copy control in C++ requires three elements: a copy constructor an assignment operator a destructor Whenever one defines a copy constructor, one must also define an assignment operator and a destructor. 269

We need an explicit assignment operator! 270

The Explicit Assignment Operator When the assignment operator is invoked, then all instance variables are initialized in the beginning. We need to release the memory first! 271

Explicit Assignment Operator in Use 272

What Has Happened? Deep copy: s2.fcharacters!= s1.fcharacters 273

Cloning: Alias Control for References 274

Copying Pointers 275

What Has Happened? Shallow copy: ps2. == ps1 Double free: delete ps2, which is the same as ps1. 276

Solution: A clone() Method Destructor must be virtual! It is best to define the destructor of a class virtual always in order to avoid problems later. 277

The Use of clone() 278

Problems With Cloning The member function clone() must be defined virtual to allow for proper redefinition in subtypes. Whenever a class contains a virtual function, then its destructor is required to be defined virtual as well. The member function clone() can only return one type. When a subtype redefines clone(), only the super type can be returned. 279

Non-virtual Cloning Does Not Work! One could define clone() non-virtual and use overloading. But this does not work as method selection starts at the static type of the pointer. SimpleString* ptostring = new SubtypeOfSimpleString(); SimpleString* c1 = ptostring->clone(); // SimpleString::clone() 280

Reference-based Semantics: When Do We Destroy Objects? 281

Reference Counting A simple technique to record the number of active uses of an object is reference counting. Each time a heap-based object is assigned to a variable the object s reference count is incremented and the reference count of what the variable previously pointed to is decremented. Some compilers emit the necessary code, but in case of C++ reference counting must be defined (semi-)manually. 282

Smart Pointers: Handle 283

The Use of Handle The template class Handle provides a pointer-like behavior: Copying a Handle will create a shared alias of the underlying object. To create a Handle, the user will be expected to pass a fresh, dynamically allocated object of the type managed by the Handle. The Handle will own the underlying object. In particular, the Handle assumes responsibility for deleting the owned object once there are no longer any Handles attached to it. 284

Handle: Constructor & Destructor Create a shared counter Decrement reference count 285

Handle: addref & releaseref Increment reference count Decrement reference count and delete object if it is no longer referenced anywhere. 286

Handle: Copy Control 287

Handle: Pointer Behavior 288

Using Handle 289

Reference Counting Limits Reference Count == 1 Reference Count == 1 Reference counting fails on circular data structures like double-linked lists. Circular data structures require extra effort to reclaim allocated memory. Know solution: Mark-and-Sweep 290