Monday, 10 April 2017

Shalllow copy Deep copy

Shallow copy

class A;
  int j = 5;
endclass

class B;
  int i = 1;
  A a = new;
endclass

B b1, b2;
  b1 = new;
  b2 = new b1;
  b2.i = 10;
  b2.a.j = 7;
...

Output:
b1.i = 1
b2.i = 10
b1.a.j = 7
b2.a.j = 7


When we copy a class variable we are just copying the handle(pointer) not the object(memory). So here both the variables have same handle(pointer). This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory.

When you do shallow copy all properties of the class will be duplicated(all properties are copied to new memory locations) in new memory except for objects. Shallow copy copies only the object handles.

Deep copy

class A;
  int j = 5;
endclass

class B;
  int i = 1;
  A a = new;

  function copy(B source);
    this.i = source.i;
    this.a = new source.a
   endfunction : copy
endclass

...
B b1, b2;
  b2.copy(b1);
  b2.i = 10;
  b2.a.j = 7;
...

Output:
b1.i = 1
b2.i = 10
b1.a.j = 5
b2.a.j = 7

For Deep copy we have to explicitly create logic to copy all the property of one class to another and if it has object as a property of other class we have to allocate memory for it and then copy the same.







No comments:

Post a Comment