Presentation is loading. Please wait.

Presentation is loading. Please wait.

Operator Overloading and Memory Management. Objectives At the conclusion of this lesson, students should be able to: Overload C++ operators Explain why.

Similar presentations


Presentation on theme: "Operator Overloading and Memory Management. Objectives At the conclusion of this lesson, students should be able to: Overload C++ operators Explain why."— Presentation transcript:

1 Operator Overloading and Memory Management

2 Objectives At the conclusion of this lesson, students should be able to: Overload C++ operators Explain why it is important to correctly manage dynamically allocated storage. Write programs that correctly use * Destructors to return dynamically allocated storage to the system. * Overloaded assignment operators to make a deep copy when necessary and return dynamically allocated storage to the system. * Copy constructors to make a deep copy when necessary.

3 Operator Overloading In order to do write some of the code that Is needed to manage memory correctly, we will have to overload an operator in C++.

4 Suppose that we have a class called Region, That represents a rectangular region. Region -length: int -width: int + Region(int: int:) + getWidth( ) :int + getLength( ) :int

5 We know how to add two primitive data types together, but can we add two Regions? Region r1(4,5); Region r2(6,3); Region r3 = r1 + r2: We can, if we overload the + operator! When we overload an operator, we tell the compiler what to do when the operator is used on objects of a given class.

6 The code to overload an operator can usually be written as a member function, or as a non-member function of a class.

7 Overloading the + operator as a member Of the Region class.

8 The + operator is a binary operator – it has two operands. Some Terminology c = b + c; the left-hand operand the operator The right-hand operand

9 The + operator is a binary operator – it has two operands. Some Terminology c = b + c; The message is sent to this object. It is sometimes called the implicit object. the operator the right-hand operand is passed as a parameter to the function.

10 The function looks like this: Region Region::operator+(const Region& rho) { int newLength = length + rho.length; int newWidth = width + rho.width; Region rtnR(newWidth, newLength); }

11 Region Region::operator+(const Region& rho) { int newLength = length + rho.length; int newWidth = width + rho.width; Region rtnR(newWidth, newLength); return rtnR; } The name of the function is the word “operator” followed by the symbol + The function is a member of the Region class It returns a Region object. It is returned by value.. The function takes the right hand operand as its parameter. Remember to pass objects by constant reference.

12 The compiler generates this function call r3 = r1.operator+(r2); length = 3 width = 4 length = 5 width = 2 r1 r2 length = ? width = ? r3 = +; The message is sent to this object. This object is passed as the parameter

13 r3 = r1.operator+(r2); length = 3 width = 4 length = 5 width = 2 r1 r2 length = ? width = ? r3 = +; The message is sent to this object. This object is passed as the parameter Region Region::operator+(const Region& rho) { int newLength = length + rho.length; int newWidth = width + rho.width; Region rtnR(newWidth, newLength); } These belong to r1 (the implicit object )

14 You could write this function as a non-member function. Then it would look like this: r3 =operator+(r1, r2); length = 3 width = 4 length = 5 width = 2 r1 r2 length = ? width = ? r3 = +; This object is passed as the 1 st parameter This object is passed as the 2 nd parameter Region operator+(const Region& lho, const Region& rho) { int newLength = lho.getLength( ) + rho.getLength( ); int newWidth = lho.getWidth( ) + rho.getWidth( ); Region rtnR(newWidth, newLength); } Must use a public getter

15 When overloading an operator there are times when you cannot write the code as a member function. A good example is the stream insertion operator. It must be written a non-member function.

16 If a member function, the compiler would generate this function call cout.operator<<(const Region& r1); length = 3 width = 4 r1 cout << ; but we can’t add code to the ostream class to overload the stream insertion operator.

17 Overloading the Stream Insertion Operator

18 Because we write this code as a non-member function, it will take two parameters, like this: ostream& operator<< (ostream& out, const Region& r1); length = 3 width = 4 r1 cout << ; The function must return a stream object. The stream parameter can’t be constant … we are changing it.

19 ostream& operator<< (ostream& out, const Region& r1) { out << “Width = “ << r1.getWidth( ); out += “Length = “ << r1.getLength( ); return out; } length = 3 width = 4 r1 cout << ; Put whatever data you want into the stream. You have to use public functions in the Region class. Then just return the stream object.

20 Memory Management One of the major program design issues in C++ is memory management. The mishandling of dynamically allocated storage in C++ is among the most serious programming errors made when using the language. Many of these issues can be addressed by designing classes as Concrete Data Types.

21 Concrete Data Types One of the goals of good software development in C++ is to construct each class so that it appears, to the applications programmer, to be equivalent to a built-in type for the language. That is, it is well behaved in all of the ways that a standard built-in data type is well behaved. A C++ class written in this way has been termed a “concrete data type''. Although in detail, the implementation of a class is specific to the class, all concrete data types have a similar structure. Some author’s refer to this structure as the orthodox canonical class form.

22 C++ Programs can allocate objects in one of three memory areas. Review The run-time stack The static data area or data segment The heap or free store local variables global and static variables size and amount known at compile time storage allocated at run-time because we don’t know how much or what type of data will be stored when the program is compiled.

23 An object is allocated on the heap using the new operator. The allocated object has no name, but is referenced through a pointer returned by the new operator. Storage allocated using new must be recycled back to the heap when the storage is no longer required. Storage that is no longer accessible, but has not been returned to the heap is called a memory leak.

24 Un-initialized pointers should be set to nullptr. Pointers should also be set to nullptr after calling delete to return storage to the heap.

25 Destructors All Concrete Data Types must have a destructor if it manages resources through a pointer. When program execution reaches the end of a block in which an object was declared, the storage allocated for that object on the stack is relinquished. If a destructor is defined for the class to which the object belongs, the destructor is called first. The purpose of the destructor is to clean up any resources that the object may have acquired. The most common resource that needs to be managed is storage allocated from the heap.

26 Linked Lists The concepts discussed in this slide set will be illustrated using a linked list. Before going through the examples, it will be necessary that you understand what a linked list is and how they are used.

27 Memory Issues list 3 node 12 node 7 9 This diagram illustrates an example of a linked list. In this example, each node of the list is dynamically allocated from the heap and contains an integer value and a pointer to the next node in the list. nullptr

28 list 3 node 12 node 7 9 class List { private: Node* head; int length; public:... }; the List class just contains a pointer to the first node in the list, and an integer containing the number of elements in the list. nullptr

29 list 3 node 12 node 7 9 class Node { private: int data; Node* next; public: Node* getNext( ); … }; Each node object contains an integer data member and a pointer to the next node. The storage for each node is allocated from the heap as it is needed. nullptr

30 list 3 node 12 node 7 9 So … what happens in this case when the list object goes out of scope? With no destructor, the pointer data member in the list object is relinquished when the object goes out of scope. Without this pointer, the first node, and all subsequent nodes, become inaccessible to the program. Since the storage for these nodes is still owned by the program, we have a memory leak. some block { List myList;... blah … blah … blah... } nullptr

31 list 3 node 12 node 7 9 Can you come up with a destructor that keeps The memory leak from happening? nullptr

32 list 3 node 12 node 7 9 head length data next List::~List { } nullptr

33 list 3 node 12 node 7 9 The following destructor will solve the problem. List::~List( ) { Node* p = head; while ( p!=nullptr) { Node* pnext = p->getNext( ); delete p; p = pnext; } head length data next this function returns the value of next nullptr

34 list 3 node 12 node 7 9 List::~List( ) { Node* p = head; while ( p!=nullptr) { Node* pnext = p->getNext( ); delete p; p = pnext; } head length data next this function returns the value of next p pnext nullptr

35 list 3 node 7 9 List::~List( ) { Node* p = head; while ( p!=nullptr) { Node* pnext = p->getNext( ); delete p; p = pnext; } head length node 12 data next this function returns the value of next p pnext nullptr

36 list 3 node 7 9 List::~List( ) { Node* p = head; while ( p!=nullptr) { Node* pnext = p->getNext( ); delete p; p = pnext; } head length this function returns the value of next p pnext nullptr

37 Assignment Operator We just illustrated how to manage the memory allocated dynamically for Node objects when the list goes out of scope. However, the automatic invocation of the destructor when the object goes out of scope introduces another serious problem. Consider the following …

38 list 3 node 12 node 7 9 list_a list 2 node 21 node 6 list_b nullptr

39 list 3 node 12 node 7 9 list_a list 2 node 21 node 6 list_b list_a = list_b; the default assignment operator does a member-by member copy of each data member in the list objects. 2 Problem: The pointer to this Data has been lost. Memory Leak! nullptr

40 list 2 node 12 node 7 9 list_a list 2 node 21 node 6 list_b Now … suppose list_b goes out of scope. Our destructor, as specified, cleans up the list, returning the storage for each node to the heap. Problem: the pointer in list_a points to memory no longer owned by the program. nullptr

41 list 2 node 12 node 7 9 list_a Storage belonging to the heap. Adding insult to injury, what happens when list_a goes out of scope? this storage gets returned twice! This could totally destroy the memory manager! nullptr

42 We solve this problem by overloading the assignment operator in the List class. The assignment operator must do two things: list_a = list_b; Free the storage used by the left operand (list_a) Make a copy the entire data structure of the right operand (list_b) and point to it in the left operand -– do a deep copy.

43 list 3 node 12 node 7 9 list_a list 2 node 21 node 6 list_b nullptr Free this storage

44 list 3 list_a list 2 node 21 node 6 list_b nullptr node 21 node 6 nullptr Make a copy the entire list … 2

45 const List& List::operator=(const List& b) { if (this ==&b) return *this; it is customary to name the parameter ‘b’ always pass the operand as a constant reference return a List reference to allow multiple assignment first, check to make sure that we are not doing the assignment a = a; We don’t want to clean up storage for a if this is the case.

46 const List& List::operator=(const List& b) { if (this ==&b) return *this; Node* p = head; while (p != nullptr) { Node* pnext = p->getNext( ); delete p; p = pnext; } this code cleans up the storage allocated to the left hand list. Note: It’s the same code we wrote for the destructor.

47 Next, we are going to do the copy. We are going to do what is called a deep copy. That is, we are going to create a complete copy of the data structure that is on the right hand side. A shallow copy only copies pointers, not what they point to.

48 length = b.length; p = nullptr; Node* q = b.getHead( ); while (q != nullptr) { Node* n = new Node; n->setNext (nullptr); n->setData (q->getData( )); if (p == nullptr) head = n; else p->setNext (n); p = n; q = q->getNext ( ); } return *this; start by copying the length data. set the Node* p to nullptr we will use this later. then declare another Node* q, and set it to the head data member in list b.

49 list 2 list_a list 2 node 6 list_b q n p nullptr 21 length = b.length; P = nullptr; Node *q = b.getHead( );

50 length = b.length; p = nullptr; Node* q = b.getHead( ); while (q != nullptr) { Node* n = new Node; n->setNext (nullptr); n->setData (q->getData( )); if (p == nullptr) head = n; else p->setNext (n); p = n; q = q->getNext ( ); } return *this; Now, allocate storage for the first node in the new list. set its pointer to the next node to nullptr. get the data member of the current node in the right-hand list and store its value in this new node.

51 list 2 list_a list 2 node 6 list_b q n p nullptr 21 q points to the current node in the right hand list n points to the new node just created n -> setNext (nullptr); n -> setData (q.getData( )); Node *n = new Node; 21

52 length = b.length; p = nullptr; Node* q = b.getHead( ); while (q != nullptr) { Node* n = new Node; n->setNext (nullptr); n->setData (q.getData( )); if (p == nullptr) head = n; else p->setNext (n); p = n; q = q->getNext ( ); } return *this; If this is the first node store its pointer in the list object.

53 list 2 list_a list 2 node 6 list_b q n p nullptr 21 head if (p == NULL) head = n; 21

54 length = b.length; p = nullptr; Node* q = b.getHead( ); while (q != nullptr) { Node* n = new Node; n->setNext (nullptr); n->setData (q.getData( )); if (p == nullptr) head = n; else p->setNext (n); p = n; q = q->getNext ( ); } return *this; set to point to the end node in left hand list, the one we just created set to point to the next node in the right hand list.

55 list 2 list_a list 2 node 6 list_b q n p nullptr head p = n; 21 q = q->getNext( );

56 We have copied the List Object and the first Node. Since q is not null (it points to a node) go through the while block again.

57 list 2 list_a list 2 node list_b list_a = list_b; q n p nullptr head 21 Node* n = new Node; n->setNext (nullptr); n->setData (q.getData( )); nullptr 6

58 list 2 list_a list 2 node list_b list_a = list_b; q n p head 21 nullptr 6 6 else p->setNext (n); p is not null, so … nullptr p = n; q = q->getNext ( );

59 We have successfully copied the second node from the right-hand list. q is now = nullptr, so we drop out of the loop.

60 Copy Constructor We have fixed the assignment operator so that is correctly creates a copy of the object. However, objects also get copied when passed by value. When a function is called, all of the function arguments are copied into local variables associated with the function. When the function exits, these variables go out of scope and are destroyed. This will cause similar problems to the ones we just discussed with the default assignment operator.

61 list_a 3 node 12 node 7 9 Consider the list shown. What happens in the function invocation double average (List a);

62 list_a 3 node 12 node 7 9 stack when the function is called, a copy of the list object goes on the stack. The default is a shallow copy …. 3

63 list_a 3 node 12 node 7 9 stack when the function exits, all of the variables associated with the function go out of scope. This includes the copy of the list object passed on the stack. When it goes out of scope, its destructor is called … 3 Oh-oh!

64 The Copy Constructor List::List(const List& b) { length = b.length; Node* p =nullptr; Node* q = b.head; while (q != nullptr) { Node* n = new Node; n->getNext (nullptr); n->setData (q->getData( )); if (p == nullptr) head = n; else p->setNext (n); p = n; q = q.getNext( ); } If this looks familiar, it is because it is the same code we used to copy the object in the overloaded assignment operator. this is a copy constructor because it takes an object of its own type as a parameter. the compiler invokes this code automatically whenever it needs to create a copy of the object.

65 Copy Constructor It is important to note that like a normal constructor, the function of the copy constructor is to initialize the data members of the object that just got created. The compiler generates the code to create the object when you do a pass by value.

66 Factoring Common Code There is a lot of common code between the destructor, the assignment operator, and the copy constructor. We can factor this common free and copy code out. Then the destructor, copy constructor, and assignment operator look as shown in the following slide.

67 List::List (const List& b) { copy(b); } List::~List( ) { free( ); } const List& List::operator=(const List& b) { if (this != &b) { free( ); copy(b); } return *this; }


Download ppt "Operator Overloading and Memory Management. Objectives At the conclusion of this lesson, students should be able to: Overload C++ operators Explain why."

Similar presentations


Ads by Google