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

前端 未结 4 713
故里飘歌
故里飘歌 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:12

    An object only needs to copy what it needs to copy. Though this question is marked language agnostic, and you mentioned C++, I prefer to explain in C# terms (since, that's what I'm most familiar with). However, the concepts are similar.

    Value types are like structs. They live directly in an object instance. Therefore, when you copy the object, you have no choice but to copy the value type. So, you generally don't have to worry about those.

    Reference types are like pointers, and this is where it gets tricky. Depending on what the reference type is, you may or may not want a deep copy. A general rule of thumb is that if a reference type (as a member of the object) depends on the state of the outer object, it should be cloned. If not, and never will, it doesn't have to be.

    Another way of thinking is that an object passed in to your object from the outside probably should NOT be cloned. An object generated BY your class, should be.

    Okay, I lied, I will use some C++ since it will best explain what I mean.

    class MyClass {
        int foo;
        char * bar;
        char * baz;
    
    public: MyClass(int f, char * str) {
            this->foo = f;
            bar = new char[f];
            this->baz = str;
        }
    };
    

    With this object, there are two string buffers that need to be dealt with. The first one, bar, is created and managed by the class itself. When you clone the object, you should allocate a new buffer.

    baz, on the other hand, should not be. In fact, you can't, since you don't have enough information to do so. The pointer should just be copied.

    And, of course, foo is just a number. Just copy it, there's nothing else to worry about :)

    In summary, to answer your questions directly:

    1. 99% of the time, no. There's only one way to copy that makes sense. What that way is, however, varies.
    2. Not directly. Documenting it is a good idea, but anything internal should stay internal.
    3. Just "Deep copy". You should (Edit: ALMOST) never try to clone an object or pointer you don't control, so that's exempt from the rules :)

提交回复
热议问题