Alex Rivera | Logout

When is a shallow copy desirable (instead of a deep copy)?

Asked 2010-07-28T08:13:37.433
10

Can someone give an example of a situation where a shallow copy is needed?

Note that in some situations, shallow copy and deep copy are the same. This can happen when the object has no ownership over any of its subvariables; that is, all subvariables are aggregated. I'd like to see examples where the an object is composed from variables which it owns, and it still is desirable to copy them shallowly.

Remark: I don't care in which language the examples are given. I'm asking this question from a C++/Java/C# point of view, although I think copying is a language agnostic concept.

Edit
Report

2 Answers

3

One possible use case is when the composed objects can be derived from state information that is present in the shallow copy and you want, for instance, to serialize your object.

You can store the shallow copy and then rebuild the complete object from the state upon deserialization.

answered 2010-07-28T08:20:56.613
3
class Element{
}

class Example {
    private List<Element> elementList = new ArrayList<Element();

    public List<Element> getElementList() {
        return new ArrayList<Element>(this.elementList);
    }

    public void addElement(Element e) {
        elementList.add(e);
    }

    public void removeElement(Element e) {
        elementList.remove(e);
    }
}

You want all modifications of Example.elementList to be done by object methods, but you want to expose elements stored in list. So you create getter which returns a shallow copy. Copy, because you don't want caller to modify object's list and shallow because you want to expose objects from list, not their copies.

answered 2010-07-28T09:43:39.840

Your Answer