Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dynamic Memory Copy Challenge

Similar presentations


Presentation on theme: "Dynamic Memory Copy Challenge"— Presentation transcript:

1 Dynamic Memory Copy Challenge
CSCE 121 J. Michael Moore

2 Assignment Output: (7, 3) 11 int a = 7; int b = 3; cout << "(" << a << ", " << b <<")"<<endl; int c; c = b; c = 11; cout << c << endl;

3 Assignment Expectation is that information is copied.
Expectation is that changes to the copy do not affect the source.

4 Assignment Output: (7, 3) (7, 11) 11
int* d = new int(7); int* e = new int(3); cout << "(" << *d << ", " << *e <<")"<<endl; int* f; f = e; *f = 11; cout << *f << endl;

5 Copy happens with pointers!
Pointer address is copied Unfortunately, both now point to the same memory address.

6 Shallow vs. Deep Copy Shallow Copy Deep Copy b ← a
b is assigned with a Shallow Copy Deep Copy a 7 a 7 b b 7

7 Shallow Copy output identifier stack heap
class TwoNums { int* num1; int* num2; public: TwoNums(int x, int y): num1(new int(x)), num2(new int(y)) {} // stuff }; int main() { TwoNums a(4, 7); TwoNums b = a; } num1 b 7 num2 num1 a num2 4 identifier stack heap

8 Deep Copy output identifier stack heap 7
class TwoNums { int* num1; int* num2; public: TwoNums(int x, int y): num1(new int(x)), num2(new int(y)) {} // stuff }; int main() { TwoNums a(4, 7); TwoNums b = a; } 4 num1 b 7 num2 num1 a num2 4 identifier stack heap

9 Assigning Class Objects
By default each data member is copied. Pointer addresses are copied, i.e. shallow copy. After copy, each identifier has the same value(s) uses the same memory address Expectation is a deep copy. uses a different memory address We can ensure deep copy happens. We’ll see how soon!


Download ppt "Dynamic Memory Copy Challenge"

Similar presentations


Ads by Google