Xiaoyan Li, 2007 1 CSC211 Data Structures Lecture 8 Dynamic Classes and the Law of the Big Three...
-
Upload
cornelius-ross -
Category
Documents
-
view
215 -
download
0
description
Transcript of Xiaoyan Li, 2007 1 CSC211 Data Structures Lecture 8 Dynamic Classes and the Law of the Big Three...
Xiaoyan Li, 2007Xiaoyan Li, 2007 11
CSC211 Data Structures
Lecture 8Lecture 8Dynamic Classes and Dynamic Classes and
the Law of the Big Threethe Law of the Big Three
Instructor: Prof. Xiaoyan LiInstructor: Prof. Xiaoyan LiDepartment of Computer Science Department of Computer Science
Mount Holyoke CollegeMount Holyoke College
Xiaoyan Li, 2007Xiaoyan Li, 2007 22
Review:
PointersPointers *(asterisk) and &(ampersand) operators*(asterisk) and &(ampersand) operators
Dynamic Variables and Dynamic Variables and newnew Operator Operator Dynamic Arrays and Dynamic ObjectsDynamic Arrays and Dynamic Objects Stack (local) vs. heap (dynamic) memoryStack (local) vs. heap (dynamic) memory
Garbage Collection and Garbage Collection and deletedelete Operator Operator Parameters revisitedParameters revisited
Pointers and Arrays as ParametersPointers and Arrays as Parameters
Xiaoyan Li, 2007Xiaoyan Li, 2007 33
Why Dynamic Classes
Limitation of our bag classLimitation of our bag class bag::CAPACITY constant determines the capacity of bag::CAPACITY constant determines the capacity of
every bagevery bag wasteful and hard to reusewasteful and hard to reuse
Solution: Solution: provide control over size in running time, byprovide control over size in running time, by pointers and dynamic memorypointers and dynamic memory => dynamic arrays=> dynamic arrays => dynamic classes=> dynamic classes
Xiaoyan Li, 2007Xiaoyan Li, 2007 44
Dynamic Classes New Features (Ch 4.3–4)
Pointers Member VariablesPointers Member Variables Dynamic Memory Allocation (where and how)Dynamic Memory Allocation (where and how) Value Semantics (what’s new?)Value Semantics (what’s new?)
assignment operator overloadingassignment operator overloading your own copy constructoryour own copy constructor
Introducing Introducing DestructorDestructor Conclusion: Conclusion: the Law of the Big Threethe Law of the Big Three
Xiaoyan Li, 2007Xiaoyan Li, 2007 55
Pointer Member Variable
The Static The Static bagbag The Dynamic The Dynamic bagbag
// From bag1.h in Section 3.1class bag{public: static const size_t CAPACITY = 20; ...private: value_type data[CAPACITY]; size_type used;};
// From bag2.h in Section 4.3class bag{public: ...private: value_type *data; size_type used; size_type capacity;};
Xiaoyan Li, 2007Xiaoyan Li, 2007 66
Invariant of the Dynamic bag
the number of items is in the member the number of items is in the member variable variable usedused
The actual items are stored in a partially The actual items are stored in a partially filled array. The array is a dynamic array, filled array. The array is a dynamic array, pointed to by the pointer variable pointed to by the pointer variable datadata
The total size of the dynamic array is the The total size of the dynamic array is the member variable member variable capacitycapacity
Where do you document the invariant?Where do you document the invariant?Rules of implementation...Rules of implementation...
Xiaoyan Li, 2007Xiaoyan Li, 2007 77
Allocate Dynamic Memory: Where?
In Old Member Functions (what are they?)In Old Member Functions (what are they?) (constructor, size, erase_one, erase, count, insert, (constructor, size, erase_one, erase, count, insert,
+, +=,)+, +=,) constructorconstructor – how big is the initial capacity? – how big is the initial capacity? insertinsert – if bag is full, how many more? – if bag is full, how many more? +/+= operators+/+= operators – how to combine two bags? – how to combine two bags?
New Member FunctionsNew Member Functions reservereserve – explicitly adjust the capacity – explicitly adjust the capacity
ExampleExample constructor with default sizeconstructor with default size
Xiaoyan Li, 2007Xiaoyan Li, 2007 88
Allocate Dynamic Memory: How?
In In constructorconstructor:: why initialize?why initialize? how?how?
defaultdefault specific sizespecific size
// From bag2.h in Section 4.3class bag{public:
static const size_t DEFAULT_CAPACITY = 20;bag(size_type init_cap = DEFAULT_CAPACITY);
...private: value_type *data; size_type used; size_type capacity;};
// From implementation file bag2.cxxbag::bag(size_type init_cap){ data = new value_type[init_cap]; capacity = init_cap; used = 0;}
Xiaoyan Li, 2007Xiaoyan Li, 2007 99
Dynamic Classes New Features (Ch 4.3–4)
Pointers Member VariablesPointers Member Variables Dynamic Memory Allocation (where and how)Dynamic Memory Allocation (where and how) Value Semantics (what’s new?)Value Semantics (what’s new?)
assignment operator overloadingassignment operator overloading your own copy constructoryour own copy constructor
Introducing Introducing DestructorDestructor Conclusion: Conclusion: the Law of the Big Threethe Law of the Big Three
Xiaoyan Li, 2007Xiaoyan Li, 2007 1010
Value Semantics
Assignment operatorAssignment operator y = x;y = x;
Copy constructorCopy constructor bag y(x); // bag y = x;bag y(x); // bag y = x;
Automatic assignment operator and copy constructorAutomatic assignment operator and copy constructor copy all the member variables (data, used, capacity) copy all the member variables (data, used, capacity)
from object x to object yfrom object x to object y but our days of easy contentment are done!but our days of easy contentment are done!
Xiaoyan Li, 2007Xiaoyan Li, 2007 1111
Failure in auto assignment operator
xxbag x(4), y(5);x.insert(18);x.insert(19);y=x;x.insert(20);
44 00 984984
capacity used datacapacity used data
yy 55 00 964964
?? ?? ?? ??
?? ?? ?? ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
Question: What will happen after executing lines 2 – 5?Question: What will happen after executing lines 2 – 5?
Xiaoyan Li, 2007Xiaoyan Li, 2007 1212
Failure in auto assignment operator
xxbag x(4), y(5);x.insert(18);x.insert(19);y=x;x.insert(20);
44 22 984984
capacity used datacapacity used data
yy 55 00 964964
1818 1919 ?? ??
?? ?? ?? ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
Question: What will happen after executing lines 2 – 5?Question: What will happen after executing lines 2 – 5?
Xiaoyan Li, 2007Xiaoyan Li, 2007 1313
Failure in auto assignment operator
xxbag x(4), y(5);x.insert(18);x.insert(19);y=x;x.insert(20);
44 22 984984
capacity used datacapacity used data
yy 44 22 984984
1818 1919 ?? ??
?? ?? ?? ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
Question: What will happen after executing lines 2 – 5?Question: What will happen after executing lines 2 – 5?
lost memorylost memory
Xiaoyan Li, 2007Xiaoyan Li, 2007 1414
Failure in auto assignment operator
xxbag x(4), y(5);x.insert(18);x.insert(19);y=x;x.insert(20);
44 33 984984
capacity used datacapacity used data
yy 44 22 984984
1818 1919 2020 ??
?? ?? ?? ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
Consequence: Change to x’ array will also change y’s array Consequence: Change to x’ array will also change y’s array
lost memorylost memory
Xiaoyan Li, 2007Xiaoyan Li, 2007 1515
If we want y to have its own dynamic array
xxbag x(4), y(5);x.insert(18);x.insert(19);y=x;x.insert(20);
44 22 984984
capacity used datacapacity used data
yy 55 00 964964
1818 1919 ?? ??
?? ?? ?? ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
Xiaoyan Li, 2007Xiaoyan Li, 2007 1616
Dynamic memory allocation is needed
xxbag x(4), y(5);x.insert(18);x.insert(19);y=x;x.insert(20);
44 22 984984
capacity used datacapacity used data
yy 44 22 964964
1818 1919 ?? ??
?? ?? ?? ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
Answer: overloading the assignment operator =Answer: overloading the assignment operator =memory de-allocatedmemory de-allocated
1818 1919 ?? ??
Xiaoyan Li, 2007Xiaoyan Li, 2007 1717
Dynamic memory allocation is needed
xxbag x(4), y(5);x.insert(18);x.insert(19);y=x;x.insert(20);
44 22 984984
capacity used datacapacity used data
yy 44 22 964964
1818 1919 2020 ??
?? ?? ?? ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
Answer: overloading the assignment operator =Answer: overloading the assignment operator =memory de-allocatedmemory de-allocated
1818 1919 ?? ??
Xiaoyan Li, 2007Xiaoyan Li, 2007 1818
Solution: overloading assignment operator
Your own assignment operatorYour own assignment operator C++ Requires the overloaded assignment C++ Requires the overloaded assignment
operator to be a member functionoperator to be a member functionbag x, ybag x, y; // OR ; // OR bag x(4), y(5);bag x(4), y(5); // OR.... // OR....y=x; // y.operator=(x); y=x; // y.operator=(x);
void bag::operator=(const bag& source)// Postcondition: The bag that activated this function
has the same items and capacity as source
A 5-minute Quiz: write your own implementation - turn inA 5-minute Quiz: write your own implementation - turn in
// From bag2.h in Section 4.3class bag{public:
static const size_t DEFAULT_CAPACITY = 20;bag(size_type init_cap = DEFAULT_CAPACITY);
...private: value_type *data; size_type used; size_type capacity;};
// From implementation file bag2.cxxbag::bag(size_type init_cap){ data = new value_type[init_cap]; capacity = init_cap; used = 0;}
Xiaoyan Li, 2007Xiaoyan Li, 2007 1919
Implementation of operator=
y = x;y = x; y y *this *this x x source source
void bag::operator =(const bag& source) // Library facilities used: algorithm {
value_type *new_data;
// Check for possible self-assignment:if (this == &source)
return;
// If needed, allocate an array with a different size:if (capacity != source.capacity){ new_data = new value_type[source.capacity]; delete [ ] data; // make sure all valid before delete!!! data = new_data; capacity = source.capacity;}
// Copy the data from the source array:used = source.used;copy(source.data, source.data + used, data);
}
Xiaoyan Li, 2007Xiaoyan Li, 2007 2020
The 2nd part of the value semantics
copy constructor copy constructor
Xiaoyan Li, 2007Xiaoyan Li, 2007 2121
Auto Copy Constructor: shallow copy
xxbag x(4)bag y(x);x.insert(18);x.insert(19);
44 00 984984
capacity used datacapacity used data
yy 44 00 984984
?? ?? ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
The only difference with auto assignment is:The only difference with auto assignment is:
y does not have its own datay does not have its own data
Xiaoyan Li, 2007Xiaoyan Li, 2007 2222
Failure in auto copy constructor
xxbag x(4);bag y(x);x.insert(18);x.insert(19);
44 22 984984
capacity used datacapacity used data
yy 44 00 984984
1818 1919 ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
change to x also changes ychange to x also changes y
Xiaoyan Li, 2007Xiaoyan Li, 2007 2323
Deep copy: providing your own copy constructor
QuestionsQuestions on Implementation ( on Implementation (homework!homework!)) do you need to check self-copydo you need to check self-copy
bag y(x); // never have bag y(y);bag y(x); // never have bag y(y); do you need to delete old bag?do you need to delete old bag?
QuestionsQuestions on Usage on Usage 4 different ways that copy constructor is used4 different ways that copy constructor is used
bag::bag(const bag& source)// Postcondition: The bag that has been constructed
has the same items and capacity as source
Xiaoyan Li, 2007Xiaoyan Li, 2007 2424
Four common situations
DeclarationDeclaration bag y(x);bag y(x);
Declaration with Alternate SyntaxDeclaration with Alternate Syntax bag y = x ;bag y = x ;
Returning an object from a functionReturning an object from a function bag union(const bag& s1, const bag& s2);bag union(const bag& s1, const bag& s2);
Value parameter is an objectValue parameter is an object void temp_bag_copy(bag clone);void temp_bag_copy(bag clone);
Xiaoyan Li, 2007Xiaoyan Li, 2007 2525
What’s missing?
allocate dynamic memory via new,allocate dynamic memory via new,take care of the value semantics,take care of the value semantics,
....?....?
Xiaoyan Li, 2007Xiaoyan Li, 2007 2626
De-allocation of dynamic memory
Return an object’s dynamic memory to the Return an object’s dynamic memory to the heap when the object is no longer in useheap when the object is no longer in use
Where and How? – Two waysWhere and How? – Two ways Take care of it yourself Take care of it yourself
delete dynamic delete dynamic datadata of an object after you’re done of an object after you’re done with itwith it
let the program do it automatically let the program do it automatically destructordestructor
Xiaoyan Li, 2007Xiaoyan Li, 2007 2727
Destructor
The primary purpose is to return an object’s The primary purpose is to return an object’s dynamic memory to the heap, and to do other dynamic memory to the heap, and to do other “cleanup”“cleanup”
Three unique features of the destructorThree unique features of the destructor The name of the destructor is always ~ followed by the The name of the destructor is always ~ followed by the
class name;class name; No parameters, no return values;No parameters, no return values; Activated automatically whenever an object becomes Activated automatically whenever an object becomes
inaccessibleinaccessible Question: when this happens?Question: when this happens?
bag::~bag(){
delete [ ] data;}
Xiaoyan Li, 2007Xiaoyan Li, 2007 2828
Destructor
Some common situations causing automatic Some common situations causing automatic destructor activationdestructor activation Upon function return, objects as local variables Upon function return, objects as local variables
destroyed;destroyed; Upon function return, objects as value parameters Upon function return, objects as value parameters
destroyed;destroyed; when an object is explicitly deletedwhen an object is explicitly deleted
Question: shall we put destructor in how-to-use-a-Question: shall we put destructor in how-to-use-a-bag documentation?bag documentation?
bag::~bag(){
delete [ ] data;}
Xiaoyan Li, 2007Xiaoyan Li, 2007 2929
The Law of the Big Three
Using dynamic memory requires the following Using dynamic memory requires the following three things all togetherthree things all together a destructora destructor a copy constructor (and of course an ordinary one)a copy constructor (and of course an ordinary one) an overloaded assignment operatoran overloaded assignment operator
In other words, the three functions come in a set – In other words, the three functions come in a set – either you need to write all three yourself, or you either you need to write all three yourself, or you can rely on the compiler-supplied automatic can rely on the compiler-supplied automatic versions of all the three.versions of all the three.
Xiaoyan Li, 2007Xiaoyan Li, 2007 3030
What will happen if not?
If we only have a constructor and a If we only have a constructor and a destructor, but do not provide a copy destructor, but do not provide a copy
constructor and an overloaded constructor and an overloaded assignment operator assignment operator
Xiaoyan Li, 2007Xiaoyan Li, 2007 3131
Importance of the Law of Big-3
bag *x, *y;x = new bag(4);y = new bag(5);x->insert(18);x->insert(19);*y = *x;delete x;y->insert(20);
Question: What will happen after executing lines 1 – 8?Question: What will happen after executing lines 1 – 8?
// destructorbag::~bag(){
delete [ ] data;}
// constructorbag::bag(size_type init_cap){ data = new value_type[init_cap]; capacity = init_cap; used = 0;}
Xiaoyan Li, 2007Xiaoyan Li, 2007 3232
Importance of the Law of Big-3
**xxbag *x, *y;x = new bag(4);y = new bag(5);x->insert(18);x->insert(19);*y = *x;delete x;y->insert(20);
44 00 984984
capacity used datacapacity used data
**yy 55 00 964964
?? ?? ?? ??
?? ?? ?? ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
allocate memory for objects (*x, allocate memory for objects (*x, *y) and their dynamic arrays*y) and their dynamic arrays
// From implementation file bag2.cxxbag::bag(size_type init_cap){ data = new value_type[init_cap]; capacity = init_cap; used = 0;}
Xiaoyan Li, 2007Xiaoyan Li, 2007 3333
Importance of the Law of Big-3
bag *x, *y;x = new bag(4);y = new bag(5);x->insert(18);x->insert(19);*y = *x;delete x;y->insert(20);
44 22 984984
capacity used datacapacity used data
55 00 964964
1818 1919 ?? ??
?? ?? ?? ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
Insert two items in the dynamic array of object *xInsert two items in the dynamic array of object *x
**xx
**yy
Xiaoyan Li, 2007Xiaoyan Li, 2007 3434
Importance of the Law of Big-3
44 22 984984
capacity used datacapacity used data
44 22 984984
1818 1919 ?? ??
?? ?? ?? ?? ??
[0] [1] [2] [3][0] [1] [2] [3]
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
automatic assignment only copies three variables automatic assignment only copies three variables (capacity, used and data) from *x to *y(capacity, used and data) from *x to *y
lost memorylost memory
bag *x, *y;x = new bag(4);y = new bag(5);x->insert(18);x->insert(19);*y = *x;delete x;y->insert(20);
**xx
**yy
Xiaoyan Li, 2007Xiaoyan Li, 2007 3535
Importance of the Law of Big-3
44 22 984984 ?? ?? ?? ?? ??
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
Deleting x will also delete the dynamic Deleting x will also delete the dynamic array of *x by calling the destructorarray of *x by calling the destructor
dangling pointerdangling pointer
lost memorylost memory
bag *x, *y;x = new bag(4);y = new bag(5);x->insert(18);x->insert(19);*y = *x;delete x;y->insert(20); bag::~bag()
{delete [ ] data;
}
**yy
Xiaoyan Li, 2007Xiaoyan Li, 2007 3636
Importance of the Law of Big-3
**yy 44 22 984984 ?? ?? ?? ?? ??
[0] [1] [2] [3] [4][0] [1] [2] [3] [4]
Your program crashes: *y needs its own copy of data !!!Your program crashes: *y needs its own copy of data !!!
dangling pointerdangling pointer
lost memorylost memory
bag *x, *y;x = new bag(4);y = new bag(5);x->insert(18);x->insert(19);*y = *x;delete x;y->insert(20);
Xiaoyan Li, 2007Xiaoyan Li, 2007 3737
Reading and Programming Assignments Putting pieces togetherPutting pieces together
bag2.h, bag2.cxx both in textbook and bag2.h, bag2.cxx both in textbook and onlineonline Self-test exercisesSelf-test exercises
16 - 2316 - 23 After-class reading (string)After-class reading (string)
Section 4.5, Self-Test 26- 32 (within exam scope)Section 4.5, Self-Test 26- 32 (within exam scope) Programming Assignment 2 Due today!Programming Assignment 2 Due today! Assignment 3 will be online tonight, due Oct 15(Mondy)Assignment 3 will be online tonight, due Oct 15(Mondy) Next Class: Exam review Next Class: Exam review Oct 10Oct 10thth Wednesday Wednesday: First in-class Exam: First in-class Exam