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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)