0

Let's say you have the following struct:

typedef struct {
    int age;
} Child;

typedef struct {
    int age;
    Child firstChild;
} Parent;

int main() {
    Parent p1 = {5, {3}};
    Parent p2 = p1;
}

When you copy p1 to p2, are you performing a shallow copy on both fields or only the Child field? My guess is that age is copied by value, but firstChild is shallow copied.

Acorn
  • 24,970
  • 5
  • 40
  • 69
Taseen A
  • 49
  • 5
  • 1
    The copy here is not shallow at all. Both structures will have their own copies of all the fields with identical values. Stucture assignment is pretty similar to `memcpy`-ing one to the other. – Eugene Sh. Feb 20 '20 at 17:04
  • 1
    There are no pointers here, so there's no such thing as a "deep" copy. – Lee Daniel Crocker Feb 20 '20 at 17:23

1 Answers1

2

Everything will be copied except (perhaps) alignment bits.

When you have pointers, then the value of the pointer will be copied (the address), not what they point to. This is what you could call "shallow".

Acorn
  • 24,970
  • 5
  • 40
  • 69
  • Does standard says member by member copy or just a `memcopy`? And what happens for uninitialized members? – TruthSeeker Feb 20 '20 at 17:27
  • @TruthSeeker: The Standard grants implementations enormous latitude on the presumption that they will use it to best serve their customers. It states that a struct copy may arbitrarily copy or ignore padding, and more significantly fails to specify what may happen if a struct being copied has uninitialized members. – supercat Feb 21 '20 at 23:42
  • @supercat: As I got to know from other [thread](https://stackoverflow.com/a/60113134/4139593) it is UB in CPP, but didn't find relevant info from [C INTERNATIONAL STANDARD](http://port70.net/~nsz/c/c11/n1570.html#Contents) – TruthSeeker Feb 22 '20 at 06:58