Default assignment operator= in c++ is a shallow copy?

前端 未结 8 2186
挽巷
挽巷 2020-12-14 05:42

Just a simple quick question which I couldn\'t find a solid answer to anywhere else. Is the default operator= just a shallow copy of all the class\' members on the right ha

8条回答
  •  误落风尘
    2020-12-14 06:27

    I'd say, default operator= is a copy. It copies each member.

    The distinction between a shallow copy and a deep copy doesn't arise unless the members being copied are some kind of indirection such as a pointer. As far as the default operator= is concerned, it's up to the member being copied what "copy" means, it could be deep or shallow.

    Specifically, though, copying a raw pointer just copies the pointer value, it doesn't do anything with the referand. So objects containing pointer members are shallow-copied by default operator=.

    There are various efforts at writing smart pointers that perform clone operations on copying, so if you use those everywhere in place of raw pointers then the default operator= will perform a deep copy.

    If your object has any standard containers as members, then it may be confusing to (for example) a Java programmer to say that operator= is a "shallow copy". In Java a Vector member is really just a reference, so "shallow copy" means that Vector members aren't cloned: source and destination refer to the same underlying vector object. In C++ a vector member will be copied, along with its contents, since the member is an actual object not a reference (and vector::operator= guarantees the contents are copied with it).

    If your data member is a vector of pointers, then you don't have either a deep copy or a shallow copy. You have a semi-deep copy, where the source and destination objects have separate vectors, but the corresponding vector elements from each still point to the same, uncloned object.

提交回复
热议问题