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.

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

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++ classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
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.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Review of C++ Programming Part II Sheng-Fang Huang.
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.
OOP Languages: Java vs C++
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
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
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
CS352-Week 2. Topics Heap allocation References Pointers.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
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.
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.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
C++ Memory Overview 4 major memory segments Key differences from Java
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
The Big Three Based on Weiss “Data Structures and algorithm Analysis CS240 Computer Science II.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
More C++ Features True object initialisation
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
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:
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
Chapter 9 Classes: A Deeper Look, Part I Part II.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
Object Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator.
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.
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.
The Assignment Operator. Rule of Three Any object which manages memory needs: – Custom Destructor – Custom Copy Constructor – Custom Assignment Operator.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
Learners Support Publications Constructors and Destructors.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Motivation for Generic Programming in C++
Constructors and Destructors
Memory Management with Classes
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Andy Wang Object Oriented Programming in C++ COP 3330
Programming with ANSI C ++
C++ Memory Management Idioms
Memberwise Assignment / Initialization
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Constructors and destructors
Constructors and Destructors
Destruction and Copying
9-10 Classes: A Deeper Look.
Destruction and Copying
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
9-10 Classes: A Deeper Look.
SPL – PS3 C++ Classes.
Presentation transcript:

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 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 first 3 operations and will defer the others (introduced in C++11) until next time –The others depend on the new C++11 move semantics

CSE 332: C++ copy control I Basic Copy Control Operations A copy constructor or copy-assignment operator takes a reference to a (usually const) instance of the class –Copy constructor initializes a new object from it –Copy-assignment operator sets object’s value from it –In either case, original the object is left unchanged (which differs from the move versions of these operations) –Destructor takes no arguments (except implicit this ) Copy control operations for built-in types –Copy construction and copy-assignment copy values –Destructor of built-in types does nothing (is a “no-op”) Compiler-synthesized copy control operations –Just call that same operation on each member of the object –Uses defined/synthesized definition of that operation for user-defined types (see above for built-in types)

CSE 332: C++ copy control I Preventing or Allowing Basic Copy Control Old (C++03) way to prevent compiler from generating a default constructor, copy constructor, destructor, or assignment operator was somewhat awkward –Declare private, don’t define, don’t use within class –This works, but gives cryptic linker error if operation is used New (C++11) way to prevent calls to any method –End the declaration with = delete (and don’t define) –Compiler will then give an intelligible error if a call is made C++11 allows a constructor to call peer constructors –Allows re-use of implementation (through delegation) –Object is fully constructed once any constructor finishes C++11 lets you ask compiler to synthesize operations –Explicitly, but only for basic copy control, default constructor –End the declaration with = default (and don’t define)

CSE 332: C++ copy control I Shallow Copy Construction There are two ways to “copy” –Shallow: re-aliases existing resources E.g., by copying the address value from a pointer member variable –Deep: makes a complete and separate copy I.e., by following pointers and deep copying what they alias Version above shows shallow copy –Efficient but may be risky (why?) –Usually want no-op destructor, aliasing via shared_ptr // just uses the array that’s already in the other object IntArray::IntArray(const IntArray &a) :size_(a.size_), values_(a.values_) { }

CSE 332: C++ copy control I Deep Copy Construction This code shows deep copy –Safe: no shared aliasing, exception aware initialization –But may not be as efficient as shallow copy in many cases 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 necessary i.e., constructors, destructors establish needed invariants // makes its own copy of the array IntArray::IntArray(const IntArray &a) :size_(0), values_(nullptr) { if (a.size_ > 0) { // new may throw bad_alloc, // set size_ after it succeeds values_ = new int[a.size_]; size_ = a.size_; // could use memcpy instead for (size_t i = 0; i < size_; ++i) { values_[i] = a.values_[i]; }

CSE 332: C++ copy control I Swap Trick for Copy-Assignment Cleanup/assignment succeed or fail together class Array { public: Array(unsigned int) ; // assume constructor allocates memory Array(const Array &); // assume copy constructor makes a deep copy ~Array(); // assume destructor calls delete on values_ Array & operator=(const Array &a); private: size_t size_; int * values_; }; Array & Array::operator=(const Array &a) { // return ref lets us chain if (&a != this) { // note test for self-assignment (safe, efficient) Array temp(a); // copy constructor makes deep copy of a swap(temp.size_, size_); // note unqualified calls to swap swap(temp.values_, values_); // (do user-defined or std::swap) } return *this; // previous *values_ cleaned up by temp’s destructor }

CSE 332: C++ copy control I Constructors and Destructors are Inverses Constructors initialize –At the start of each object’s lifetime –implicitly called when object is created Destructors clean up –Implicitly called when an object is destroyed E.g., when stack frame where it was declared goes out of scope E.g., when its address is passed to delete E.g., when another object of which it is a member is being destroyed IntArray::IntArray(unsigned int u) : size_(0), values_(nullptr) { // exception safe semantics values_ = new int [u]; size_ = u; } IntArray::~IntArray() { // deallocates heap memory // that values_ points to, // so it’s not leaked: // with deep copy, object // owns the memory delete [] values_; // the size_ and values_ // member variables are // themselves destroyed // after destructor body }

CSE 332: C++ copy control I More on Initialization and Destruction Initialization follows a well defined order –Base class constructor is called That constructor recursively follows this order, too –Member constructors are called In order members were declared Good style to list in that order (a good compiler may warn if not) –Constructor body is run Destruction occurs in the reverse order –Destructor body is run, then member destructors, then base class destructor (which recursively follows reverse order) Make destructor virtual if members are virtual –Or if class is part of an inheritance hierarchy –Avoids “slicing”: ensures destruction starts at the most derived class destructor (not at some higher base class)