Shallow copy
-
hi can someone tell me exactly what a shallow copy does it or is it a refrence is it good or bad to use ;)
Say you have a structure that looks like this:
struct
{
int x ;
char* p ;
} ;If you copy an instance of this structure, the int will copy fine since it is a simple data type but the char* pointer causes problems. If you just copy the value of p over (a shallow copy), you will have two instances of your structure that have a pointer to the same string. This causes problems when cleaning up - who has responsibility for free'ing the string? You don't want to do it twice. A deep copy does an intelligent copy - it will make copies of the structure's data members where necessary. In this case, it will allocate a new block of memory and copy the string data over.
"Sucks less" isn't progress - Kent Beck [^] Awasu 1.1.3 [^]: A free RSS reader with support for Code Project.
-
hi can someone tell me exactly what a shallow copy does it or is it a refrence is it good or bad to use ;)
bhangie wrote: what a shallow copy does The copy is shallow when only the pointer is copied:
void ShallowCopy(int* a)
{
int* b;
b = a;
}The copy is deep when the value at which the pointer points is copied:
void DeepCopy(int* a)
{
int* b;
*b = *a;
}bhangie wrote: is it good or bad to use Depends on the situation. If a shallow copy is deleted, the original pointer no longer points to the expected data, which of course can be disasterous. That's one reason to implement copy constructors in C++, to ensure member pointers are copied correctly. -- Human beings, who are almost unique in having the ability
to learn from the experience of others, are also remarkable
for their apparent disinclination to do so. (Douglas Adams)