Here's an example of a copy-constructor:
1 2 3 4 5
|
class Test
{
Test(const Test &pInstance); // Copy-constructor
//...
};
|
A deep-copy is when you give each member its own copy of the data of the instance you passed it. Consider this code:
In this code,
B's copy-constructor is called with
A as its argument. For each member of
A,
B's members are given an exact copy of
A's members. However, this is not the case with DAM. When memory is involved, it's a different story. Consider this:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
struct Buffer
{
Buffer() { mMemory = new int(0); }
Buffer(const Buffer &pInstance) { mMemory = pInstance.mMemory; }
~Buffer() { delete mMemory; }
int *mMemory;
};
int main()
{
Buffer A, B(A);
}
|
What happens? when
A is constructed,
A.mMemory is assigned to DAM. When
B is constructed, its copy-constructor is called with
A as its argument. This causes
B.mMemory to point to the same location as
A.mMemory. This is where things start to go wrong. Since
A was first on the stack,
B's destructor is called first, which deletes the memory
B.mMemory points to. Following
B's destruction, comes
A's destruction.
A's destructor is called, which deletes the memory pointed to by
A.mMemory. And now: Disaster! The memory was already freed when
B's destructor was called.
By creating a deep-copy,
B.mMemory would claim its own memory.
Wazzak