Copying a value like an integer is easy. When we pass a value to a function/method, or create two variables, we simply copy the value of that integer, or whatever the primitive is.
int x = 5;
int y = 0;
x = y; // x gets the value of y, but changes to either don't affect the other
When we have custom data types, now we start to have more detailed questions. For example, do we pass a copy of the data? Or do we pass by reference?
Circle c1 = new Circle(10);
Circle c2;
c2 = c1; // is this duplicated or copy by reference
Duplicating a variable or object might seem overly simplistic and unnecessary task until you realize where you use it most often – passing variables to a function or method.
Here, you need to efficiently pass a variable, but what happens if you temporarily modify a value in your function. Does that change persist in the calling method? This depends on the type of data you pass, how it is passed, and the language itself.
- Does it matter if we have objects within an object?
- How about when we pass data to a function or method?
Shallow Copy
In a shallow copy the native data types are copied, but complex data types, like arrays, objects, etc, are copied as a reference meaning that the pointer that points to their location in memory is what is copied, not the data itself. So if one of the complex data type elements is updated, then all of the copies are updated as well.
This is why a Copy Constructor is often needed. To ensure data is actually copied.
Deep Copy
A deep copy makes a complete clone of the data, including complex types. Any data that is changed in one copy is left unchanged in the others.
Why not just make deep copies? 1) Speed 2) Memory 3) Sometimes you want a shallow copy.
Which is used is often dependent upon the language, settings, and what you the developer wants/needs. However, you will find a shallow copy is often used by default for performance reasons.
Java allows you to override the clone method of an object, to allow you to use a deep copy, or semi deep where you duplicate some values, but pass others by reference depending upon your needs. However, you are responsible for building the clone method.
In C++, and Java for the matter, you can use the Copy Constructor, or maybe even a programming methodology such as a factory to create deep copies.
C# is just one of the languages which uses an out keyword. By default parameters in C# aren’t modified, but this keyword lets data modified in the method be passed back, even though it comes through the parameter list.
Since this is something that is specific to languages, and there are so many, it is something you should probably check with your specific language, and test, to find potentially hidden bugs.
Copying Data – Deep vs Shallow was originally found on Access 2 Learn