Juha said:
The compiler cannot automatically generate a deep-copying of the
objects because it has absolutely no way of knowing whether the
member pointers are pointing at memory allocated and owned by the
object itself, or whether they are just pointing to something else
(for example trying to deep-copy an element of a doubly-linked list
would be quite a bad idea).
The default assignment operator simply assigns each individual
member variable from the parameter to this, regardless of what it
is. If it's eg. a pointer, then a simple pointer assignment will be
done. In many cases the default assignment operator is ok, especially if
the class does not contain pointers.
It returns a const-reference to *this.
This behavior is sometimes refered to as a "bitwise copy" although
that is not strictly true. If it was a bitwise copy, copying the
bits of the class ignoring constructors, then there would be
different values then there are.
Basically it will take the base copy of whatever types are being
copied. For most things this is fine. This will work for
stl::containers, std::string, std::vector, etc... but it usually does
not give you want you want for pointers. Your copied class will have
it's pointers copied by value, pointing to the same things they were
pointing to before. In some cases this may be what you want. In most
cases it is not. One of the biggest dangers of this behavior is when
the destructor of the class destroyes it's pointed to value (delete).
Then your copied class may point to data that is no longer valid.
Consider:
class Foo
{
public:
Foo() { MyData = new char[100]; }
~Foo() { delete[] MyData; }
private:
char* MyData;
}
If this class is copied, MyData will be copied by value, the pointer
will be copied, and you will have 2 instances pointing to the same
portion of memory, which is not what you want in most cases. Also,
if the destructor ever gets invoked, such as a temporary being
created and destroyed, then MyData will become invalid in the copied
class. The normal way of dealing with this is with a copy
constructor that assigns it's own memory.
#include <algorithm>
class Foo
{
public:
Foo() { MyData = new char[100]; }
~Foo() { delete[] MyData; }
Foo( const Foo& rhs )
{
MyData = new char[100];
std::copy( &rhs.MyData[0], &rhs.MyData[99], MyData );
}
private:
char* MyData;
};