Lecture 14 - John Ribeiro
typedef struct {
char *name; int year; int month; int date;
} Person;
Person Person_construct ( char * n , int y, int m, int d ) {
Person p; p.name = malloc ( sizeof(char) * ( stnlen(n) + 1 ) ); strcpy(p.name, n ); p.year = y; p.month = m; p.date = d; return p;
}
void Person_destruct ( Person p ) {
free ( p.name );
}
DEEP COPY (AVOID):
Person Person_copy ( Person p ) {
return Person_constructor(p.name, p.year, p.month, p.date);
}
Person Person_assign ( Person p1, Person p2 ) {
Person_destruct (p1); return Person_copy(p2);
}
--
Person p1 = Person_construct ("alice", 1980, 10, 21); Person p2 = Person_construct ("genny", 1984, 2, 5 ); Person p3 = Person_copy (p1); p3 = Person_assign (p3, p2);
Person_destruct(p1); Person_destruct(p2); Person_destruct(p3);
Why constructor?
- A single place where all attributes are assigned
- malloc in constructor
- destructor_copy, assign
typedef struct {
int year; int month; int date;
} DateofBirth;
typedef struct {
char *name; DateofBirth dob;
} Person;
- When Person returns, the compiler will copy attribute by attribute
If P3 = P1; // Shadow copy
A shadow copy is when two pointers are assigned the same value in memory i.e the point to the same place
int x = 24; int y = x; x = 31 y = 31;
What is y?
Copy on Write - if one pointer changes memory