Ok, I can't sleep, so I'm going to explaine shallow vs. deep copy in a little bit detail, because it's seems there are
people who don't understand this very important issue. And for those who do understand...well, it can't hurt anyway.
The default copy constructor simply copies each member variable from the object passed as a parameter to the member
variables of the new object. This is called a member-wise (or shallow) copy, and although this is fine for most member
variables, it breaks pretty quickly for member variables that are pointers to objects on the free store.
Member-wise copy copies the exact values of one object's member variables into another object.
Pointers in both objects end up pointing to the same memory.
A deep copy copies the values allocated on the heap to newly allocated memory.
If the object1 includes a pointer member variable, that points to an object on the free store, the default
copy constructor will produce soething like this:
Code:
Object 1 the heap Object 2
|---------------| |------------------| |---------------|
| pointer |------->| var |<-------| pointer |
|---------------| |------------------| |---------------|
| | | | | ... |
|---------------| |------------------| |---------------|
Now try to understand what will happen if either object1 or object2 goes out of scope.
Assume Object 1 goes out of scope (for example at the end of some function), then it's destructor is called.
If destructor frees this memory (which is very likely, because you don't want to create a memory leak)
and the Object 2 is still pointing to the memory, a stray pointer has been created and it is a possible disater in your program.
Solution is to write your own copy constructor and overload assignment operator (according to the BigThree rule) to avoid shallow copy and create deep copy.
Deep copy will produce something like this:
Code:
the heap Object 2
|------------------| |---------------|
| var |<-------| pointer |
|------------------| |---------------|
| | | ... |
|------------------| |---------------|
the heap Object 1
|------------------| |---------------|
| var |<-------| pointer |
|------------------| |---------------|
| | | ... |
|------------------| |---------------|
When you implement for instance, operator= then implementation of copy constructor becoming trivial.
One thing you should always do when implementing assignment operator is to check for self assignment (or
write clever code in which you do that implicitely) because it can be a very big problem. Why?
Well, I'll leavet that to you. There's plenty answers on the Internet and also, do a bord search.
P.S. I don't know how to do formatting like Prelude did in her tutorials, so I used code tags. Moderators are free to change it to appropriate style if they want.
- Micko