code_junkie

What is the difference between a deep copy and a shallow copy?

Nov 11th, 2011
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. class String
  2. {
  3. int size;
  4. char* data;
  5. };
  6.  
  7. String s1("Ace"); // s1.size = 3 s1.data=0x0000F000
  8.  
  9. String s2 = shallowCopy(s1);
  10. // s2.size =3 s2.data = 0X0000F000
  11. String s3 = deepCopy(s1);
  12. // s3.size =3 s3.data = 0x0000F00F
  13. // (With Ace copied to this location.)
  14.  
  15. char * Source = "Hello, world.";
  16.  
  17. char * ShallowCopy = Source;
  18.  
  19. char * DeepCopy = new char(strlen(Source)+1);
  20. strcpy(DeepCopy,Source);
  21.  
  22. var source = { firstName="Jane", lastname="Jones" };
  23. var shallow = ShallowCopyOf(source);
  24. var deep = DeepCopyOf(source);
  25. source.lastName = "Smith";
  26. WriteLine(source.lastName); // prints Smith
  27. WriteLine(shallow.lastName); // prints Smith
  28. WriteLine(deep.lastName); // prints Jones
  29.  
  30. struct sample
  31. {
  32. char * ptr;
  33. }
  34. void shallowcpy(sample & dest, sample & src)
  35. {
  36. dest.ptr=src.ptr;
  37. }
  38. void deepcpy(sample & dest, sample & src)
  39. {
  40. dest.ptr=malloc(strlen(src.ptr)+1);
  41. memcpy(dest.ptr,src.ptr);
  42. }
Add Comment
Please, Sign In to add comment