views:

69

answers:

1

Shallow copy is when i write new List<List<ClassA>>(lsA) which just copies the member ls. So shallow copies the first list while the inner list is not. Since MyList has access to each T being put in (which its just piping through with C#'s List in this example) it can do a shallow copy each of those. So now all the members of MyList is being copied and the variables it can directly access.

What kind of copy is this? Its only doing a shallow copy on its inner vars so this isnt a deep copy? since its copying vars it can touch and not just a memberwise vars its no longer a shallow copy. Is this type of copy called something? also is it bad practice since it is not a deep copy and possibly no more useful then a shallow copy?

class ClassA { int a; }
class MyList<T> { List<T> ls; /*i cheat */ }
MyList<MyList<ClassA>> lsA;
A: 

I'm really not sure what the code at the bottom is trying to say, however, here is my take anyway (and the question is not language-agnostic):

If data (objects) is/are immutable then the type of copy is mostly mute (in fact, there is no reason for a deep copy with immutable objects!). By reducing the amount of immutability I generally don't have deep copies (pretty much ever) and a 'shallow copy' using the standard constructors works well.

Note that for, say, List<T>, there is a ctor List<T>(IEnumerable<T> collection). This in turn just creates the new object adding each element from from the existing Enumerable in turn and the rules follow the standard "ref"/"struct" type behavior (remember that struct types can be boxed up in surprising ways though). Note that this constructor is not 'copying vars': rather it is copying the item object values of the Enumerable passed in (this does not imply creating a duplicate object for "ref" objects).

pst