CSE 332: C++ copy control II Copy Control (Part II) Review: copy control consists of 5 distinct operations –A copy constructor initializes an object by.

Slides:



Advertisements
Similar presentations
Chapter 18 Vectors and Arrays
Advertisements

Chapter 18 Vectors and Arrays John Keyser’s Modification of Slides by Bjarne Stroustrup

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.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
A C LOSER L OOK AT C LASSES 1. A SSIGNING O BJECTS One object can be assigned to another provided that both objects are of the same type. It is not sufficient.
CS-1030 Dr. Mark L. Hornick 1 Constructors Copy Constructors.
CSE 332: C++ classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
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.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 14: Overloading and Templates.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
Copy Control Joe Meehean. More Class Responsibilities When making a new type (i.e., class) we must specify what happens when it is: Copied Assigned Destroyed.
Pointer Data Type and Pointer Variables
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Inheritance. Recall the plant that we defined earlier… class Plant { public: Plant( double theHeight ) : hasLeaves( true ), height (theHeight) { } Plant(
Intro to C++ And Some Tools Opening Discussion zHave any questions come up since last class? Have you had a chance to look over the project.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
CS212: Object Oriented Analysis and Design Lecture 12: Operator Overloading-II.
CSE 425: Object-Oriented Programming I Object-Oriented Programming A design method as well as a programming paradigm –For example, CRC cards, noun-verb.
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
C++ Memory Overview 4 major memory segments Key differences from Java
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Object-Oriented Programming in C++ More examples of Association.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
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:
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Effective C++, 2nd Ed. By Scott Myers. Constructors, Destructors, and Assignment Operators 11.Define a copy constructor and an assignment operator for.
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.
C++ 程序语言设计 Chapter 12: Dynamic Object Creation. Outline  Object creation process  Overloading new & delete.
CSE 332: Memory management with C++ classes Memory Management with Classes Review: for non-static built-in (native) types –default constructor and destructor.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Classes - Part II (revisited) n Constant objects and member functions n Definition Form of Member Functions n friend functions and friend classes n Constructors.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
ECE 264 Object-Oriented Software Development
Learners Support Publications Constructors and Destructors.
Pointers and References. Pointers & Memory 0x000x040x080x0B0x100x140x180x1B0x20.
CS212: Object Oriented Analysis and Design Polymorphism (Using C++)
Chapter 2 Objects and Classes
Constructors and Destructors
Motivation and Overview
Andy Wang Object Oriented Programming in C++ COP 3330
Memberwise Assignment / Initialization
This pointer, Dynamic memory allocation, Constructors and Destructor
Chapter 2 Objects and Classes
CSE 303 Concepts and Tools for Software Development
Constructors and Destructors
CMPE 135: Object-Oriented Analysis and Design November 27 Class Meeting Department of Computer Engineering San Jose State University Fall 2018 Instructor:
Practical Session 4 Rule of 5 R-value reference Unique pointer
Move Semantics CSCE 121.
Pointers and References
SPL – PS2 C++ Memory Handling.
Initialization List.
SPL – PS4 C++ Advanced OOP.
Presentation transcript:

CSE 332: C++ copy control II Copy Control (Part II) Review: copy control consists of 5 distinct operations –A copy constructor initializes an object by duplicating the const l-value that was passed to it by reference –A copy-assignment operator (re)sets an object’s value by duplicating the const l-value passed to it by reference –A destructor manages the destruction of an object –A move constructor initializes an object by transferring the implementation from the r-value reference passed to it –A move-assignment operator (re)sets an object’s value by transferring the implementation from the r-value reference passed to it Today we’ll focus on the last 2 operations and other features (introduced in C++11) like r-value references –I.e., features that support the new C++11 move semantics

CSE 332: C++ copy control II Motivation for Move Semantics Copy construction and copy-assignment may be expensive due to time/memory for copying It would be more efficient to simply “take” the implementation from the passed object, if that’s ok It’s ok if the passed object won’t be used afterward –E.g., if it was passed by value and so is a temporary object –E.g., if a special r-value reference says it’s ok to take from (as long as object remains in a state that’s safe to destruct) Note that some objects require move semantics –I.e., types that don’t allow copy construction/assignment –E.g., unique_ptr, ifstream, thread, etc. New for C++11: r-value references and move function –E.g., int i; int &&rvri = std::move(i);

CSE 332: C++ copy control II Synthesized Move Operations Compiler will only synthesize a move operation if –Class does not declare any copy control operations, and –Every non-static data member of the class can be moved Members of built-in types can be moved –E.g., by std::move etc. User-defined types that have synthesized/defined version of the specific move operation can be moved L-values are always copied, r-values can be moved –If there is no move constructor, r-values only can be copied Can ask for a move operation to be synthesized –I.e., by using = default –But if cannot move all members, synthesized as = delete

CSE 332: C++ copy control II R-Values, L-Values, and References to Either A variable is an l-value (has a location) –E.g., int i = 7; Can take a regular (l-value) reference to it –E.g., int & lvri = i; An expression is an r-value –E.g., i * 42 Can only take an r-value reference to it (note syntax) –E.g., int && rvriexp = i * 42; Can only get r-value reference to l-value via move –E.g., int && rvri = std::move(i); –Promises that i won’t be used for anything afterward –Also, must be safe to destroy i (could be stack/heap/global)

CSE 332: C++ copy control II Move Constructors Note r-value reference –Says it’s safe to take a ’s implementation from it –Promises only subsequent operation will be destruction Note constructor design –A lot like shallow copy constructor’s implementation –Except, zeroes out state of a –No sharing, current object owns the implementation –Object a is now safe to destroy (but is not safe to do anything else with afterward) // takes implementation from a IntArray::IntArray(IntArray &&a) : size_(a.size_), values_(a.values_) { // make a safe to destroy a.values_ = nullptr; a.size_ = 0; }

CSE 332: C++ copy control II Move-Assignment Operators No allocation, so no exceptions to worry about –Simply free existing implementation (delete values_ ) –Then copy over size and pointer values from a –Then zero out size and pointer in a This leaves assignment complete, a safe to destroy –Implementation is transferred from a to current object Array & Array::operator=(Array &&a) { // Note r-value reference if (&a != this) { // still test for self-assignment delete [] values_; // safe to free first (if not self-assigning) size_ = a. size_; // take a’s size value values_ = a.values_; // take a’s pointer value a.size_ = 0; // zero out a’s size a.values_ = nullptr; // zero out a’s pointer (now safe to destroy) } return *this; }

CSE 332: C++ copy control II Move Semantics and Inheritance Base classes should declare/define move operations –If it makes sense to do so at all –Derived classes then can focus on moving their members –E.g., calling Base::operator= from Derived:: version Containers further complicate these issues –Containers hold their elements by value –Risks slicing, other inheritance and copy control problems So, put (smart) pointers, not objects, into containers –Access is polymorphic if destructors, other methods virtual –Smart pointers may help reduce need for copy control operations, or at least simplify cases where needed