I have a structure containing character arrays with no any other member functions. I am doing assignment operation between two instances of these structures. If I’m not mistaken, it is doing shallow copy. Is shallow copy safe in this case?
I’ve tried this in C++ and it worked but I would just like to confirm if this behavior is safe.
If by “shallow copy”, you mean that after assignment of a
structcontaining an array, the array would point to the originalstruct‘s data, then: it can’t. Each element of the array has to be copied over to the newstruct. “Shallow copy” comes into the picture if your struct has pointers. If it doesn’t, you can’t do a shallow copy.When you assign a
structcontaining an array to some value, it cannot do a shallow copy, since that would mean assigning to an array, which is illegal. So the only copy you get is a deep copy.Consider:
The above will print:
If, on the other hand, your
structhad a pointer,structassignment will only copy pointers, which is “shallow copy”:The above will print:
In general, given
struct T d1, d2;,d2 = d1;is equivalent tomemcpy(&d2, &d1, sizeof d2);, but if the struct has padding, that may or may not be copied.Edit: In C, you can’t assign to arrays. Given:
is illegal. So, as I said above, if you have an array in a
struct, assigning to the struct has to copy the data element-wise in the array. You don’t get shallow copy in this case: it doesn’t make any sense to apply the term “shallow copy” to a case like this.