Does a copy constructor/operator/function need to make clear which copy variant it implements?

前端 未结 4 736
故里飘歌
故里飘歌 2021-01-11 12:54

Yesterday I asked a question about copying objects in C#, and most answers focussed on the difference between deep copy and shallow copy, and the fact that it

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-11 13:19

    The distinction between of "deep copy" versus "shallow copy" makes sense as an implementation detail, but allow it to leak beyond that generally indicates a flawed abstraction which will likely manifest itself in other ways as well.

    If an object Foo holds an object reference purely for the purpose of encapsulating immutable aspects, other than identity, of the object contained therein, then a correct copy of Foo may either contain a duplicate of the reference or a reference to a duplicate of the encapsulated object.

    If an object Foo holds an object reference purely for the purpose of encapsulating mutable and immutable aspects of an object other than identity, but no reference to that object will ever be exposed to anything that would mutate it, the same situation applies.

    If an object Foo holds an object reference purely for the purpose of encapsulating mutable and immutable aspects of an object other than identity, and the object in question is going to be mutated, then a correct copy of Foo must contain a reference to a duplicate of the encapsulated object.

    If an object Foo holds an object reference purely for the purpose of encapsulating immutable aspects of the object including identity, then a correct copy of Foo must contain a duplicate of the reference; it must NOT contain a reference to a duplicated object.

    If an object Foo holds an object reference for the purpose of encapsulating both mutable state and object identity, then it is not possible to produce a correct copy of Foo in isolation. A correct copy of Foo may only be produced by duplicating the entire set of objects to which it is attached.

    The only time it makes sense to talk about a "shallow copy" is when an incomplete operation is used as one of the steps in making a correct copy. Otherwise, there is only one correct copy "depth", controlled by the type of state encapsulated in object references.

提交回复
热议问题