Object-Oriented Principles and Practice / C++

Similar documents
Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++

CPSC 427: Object-Oriented Programming

Assignment of Structs

CPSC 427: Object-Oriented Programming

And Even More and More C++ Fundamentals of Computer Science

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

CPSC 427: Object-Oriented Programming

Special Member Functions

CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

COMP6771 Advanced C++ Programming

CPSC 427: Object-Oriented Programming

Object-Oriented Principles and Practice / C++

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

Midterm Review. PIC 10B Spring 2018

Ch. 11: References & the Copy-Constructor. - continued -

Concepts (this lecture) CSC 143. Classes with Dynamically Allocated Data. List of ints w/dups (cont.) Example: List of ints with dups.

Programming, numerics and optimization

C++11 Move Constructors and Move Assignment. For Introduction to C++ Programming By Y. Daniel Liang

C The new standard

Object-Oriented Programming for Scientific Computing

Overview of C Feabhas Ltd 2012

Assignment of Objects

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

CSI33 Data Structures

Vector and Free Store (Vectors and Arrays)

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

Object-Oriented Principles and Practice / C++

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

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

Rvalue References & Move Semantics

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CS11 Advanced C++ Spring 2018 Lecture 2

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Determine a word is a palindrome? bool ispalindrome(string word, int front, int back) { Search if a number is in an array

A brief introduction to C++

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

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

An Introduction to C++

Vector and Free Store (Pointers and Memory Allocation)

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Advanced Systems Programming

Rvalue References, Move Semantics, Universal References

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

Instantiation of Template class

C++ - Lesson 2 This is a function prototype. a' is a function that takes an integer array argument and returns an integer pointer.

CSE 303: Concepts and Tools for Software Development

Object-Oriented Principles and Practice / C++

Object Oriented Programming COP3330 / CGS5409

CS201 Some Important Definitions

EL2310 Scientific Programming

Construction and Destruction

04-19 Discussion Notes

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

Object-Oriented Programming

Object-Oriented Principles and Practice / C++

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

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

Domains: Move, Copy & Co

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

Pointers, Dynamic Data, and Reference Types

Objects Managing a Resource

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

Chapter 17: Linked Lists

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Object Oriented Programming. Solved MCQs - Part 2

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

Function Overloading

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Assignment operator string class c++ Assignment operator string class c++.zip

Chapter 17 vector and Free Store

Constructors, Destructors, and Assignment Operators. Literature: Effective C++, Third Edition Chapter 2

Short Notes of CS201

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

CS 32. Lecture 5: Templates

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017

PIC 10B Lecture 1 Winter 2014 Homework Assignment #3

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Move semantics. Zoltán Porkoláb: C++11/14 1

CS

Chapter 17 vector and Free Store

CS201 - Introduction to Programming Glossary By

Classes and Objects. Class scope: - private members are only accessible by the class methods.

QUIZ. What is wrong with this code that uses default arguments?

The vector Class and Memory Management Chapter 17. Bjarne Stroustrup Lawrence "Pete" Petersen Walter Daugherity Fall 2007

Overview. 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43

Program construction in C++ for Scientific Computing

COMP6771 Advanced C++ Programming

CS24 Week 3 Lecture 1

COSC 2P95 Lab 5 Object Orientation

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Transcription:

Object-Oriented Principles and Practice / C++ Alice E. Fischer October 10, 2016 OOPP / C++ Lecture 7... 1/15

Construction and Destruction Kinds of Constructors Move Semantics OOPP / C++ Lecture 7... 2/15

Construction and Destruction Ch 10 Allocation and Deallocation: Review Initializing Arrays Six kinds of Constructors But just one Destructor OOPP / C++ Lecture 7... 3/15

Allocation and Deallocation Ch 10.2 The new function in C++ builds upon C s malloc. Using new or malloc results in the storage you requested + enough to handle deallocation Minimally, the total allocated block length must be stored Thus, allocating a new double uses up 12 bytes of memory, 4 for the block length and 8 for the data. For a struct, it is the overhead + enough bytes to hold the data + padding. New and malloc differ for arrays because new also allocates memory for the array length. (A total of 8 bytes of overhead) OOPP / C++ Lecture 7... 4/15

Initialization C++11 gives us new ways to initialize arrays. class Tester { private: static int a0[3]; static constexpr int a1[3]{1,2,3}; int a2[3] = {8}; int a3[3]; int* a4; int* a5 = new int[3]{5,6,7}; public: Tester(): a3(), a4(new int[3]{7,8,9}) {} } const int Tester::a1[3]; int Tester::a0[3]{4,5,6}; OOPP / C++ Lecture 7... 5/15

Six Kinds of Constructors Null constructor: initializes nothing but may print a trace comment. You get an empty null constructor for free if you do not define a real constructor. Default constructor: may do initializations but lacks parameters. Normal constructor: has parameters used to initialize the object. Default copy constructor: initializes an object by shallow-copying another. Copy constructor: replaces the default copy constructor. It can do anything, including making a full copy of the object. Move constructor: moves the contents of one object to another during initialization. OOPP / C++ Lecture 7... 6/15

Several Constructors but just one Destructor A destructor must handle every class object the same way. Thus, every object must be the same general shape and have the same number of dynamic parts (or NULL pointers) to delete. According to the standard, it is harmless to delete a NULL pointer. Nothing is supposed to happen. You do not need to test a pointer before trying to delete it. However, apparently, some implementations of C++ do not comply to the standard. Normally, a destructor should free all objects that were created by calling new in the constructor or in any other class function, or by inserting an object (created elsewhere) into a class data structure. OOPP / C++ Lecture 7... 7/15

Revisiting delete and delete[] For non-arrays, the block length is stored just before the data part (just like malloc) For arrays, the array length is stored before beginning of the data area and the block length is stored just before the array length. When you call delete it uses the block length to free memory. When you call delete[] it does two things: First, the array length is used to control a loop that calls delete on each array element. Then the block length is used to free the array allocation. OOPP / C++ Lecture 7... 8/15

An rvalue reference can bind to an rvalue (but not to an lvalue): X a; X& r1 = a; X&& rr1 = f(); X&& rr2 = a; // bind r1 to a (an lvalue) // bind rr1 to the result of f(). // error: a is an lvalue This idea can be used to speed up execution of any operation that moves values around. If X is a type for which copying is expensive (string, vector) a simple swap becomes an expensive operation. OOPP / C++ Lecture 7... 9/15

Default Class Operations: C++ 11 By default, a class has these five related operations: destructor: By default, a null destructor. copy constructor: X(const X&) Initialize a new object from an old one of the same type. The contents of the source are unchanged. copy assignment: Y& operator=(const Y&) Copy one object into another of the same type. The contents of the source are unchanged. move constructor: X(const X&&) Initialize a new object by moving the contents of an old object into it. After the move, the contents of the source are set to the initial constructed state. move assignment: Y& operator=(y&&); Move one object into another. OOPP / C++ Lecture 7... 10/15

Default Class Operations: C++ 11 Copy, move, and delete are closely related operations. You can redefine all of them, but only a few combinations make sense. If you declare any of them you must explicitly define or default all the others. If you define any one, movers will not be generated automatically. Copiers will be generated automatically, but this is deprecated. Move constructor and move assignment takes non-const &&. They can, and usually do, write to their argument OOPP / C++ Lecture 7... 11/15

Control of Defaults: C++ 11 The keywords delete and default and can be used to define methods. class X { // These definitions disallow copying. X& operator=(const X&) = delete; X(const X&) = delete; }; class X { // These define the default copy behavior. X& operator=(const X&) = default; X(const X&) = default; }; OOPP / C++ Lecture 7... 12/15

An rvalue reference can bind to an rvalue (but not to an lvalue): Classname && rref = &myclassinstance; Refer to the Brackets program for examples of all these things. OOPP / C++ Lecture 7... 13/15

RValue Swapping When we swap, we don t really want new copies at all. We just want to rebind the existing copies. void swap(t& a, T& b) { T tmp = move(a); // Save a s value. a = move(b); // Move b s value to a. b = move(tmp); // Move the saved value to b. Moving is faster than copying for many types because it does not construct a new object. This is very important when you design a template because the template parameter could be any primitive or class type. OOPP / C++ Lecture 7... 14/15

Move Semantics What we really want to do is move all of the data from one array to another, not create a duplicate copy of the data. We certainly do not want to create deep copies! The latest revision of C++ allows us to define a move constructor for each class that is different from the copy constructor. When we deep-copy an object, all of its core parts and all its extensions are duplicated. This consumes time and space. A shallow copy duplicates the core parts but not the extensions, and two copies of the core object end up pointing at the same extensions. When we move an object, we want all parts of the object in the new location, and we want any pointers in the old location nulled-out. OOPP / C++ Lecture 7... 15/15