Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Assigning structs does a member-wise assignment, and for arrays this means assigning each item. (And this is done recursively for "multiple dimension" arrays, which are really just arrays of arrays.)</p> <p>You are correct that it does a shallow copy, even on arrays. (I'm assuming that you have not overloaded op= with respect to C++; if you overload it you can do anything you want.)</p> <p>Remember that a shallow copy means copying the value of something, while a deep copy means copying the value to which something points or refers. The value of an array is each item in it.</p> <p>The difference between shallow and deep is most meaningful when you have a type that does indirection, such as a pointer. I find my answer the most helpful way to look at this issue, but you could also say "shallow" vs "deep" <em>doesn't even apply</em> to other types, and they are just "copied".</p> <pre><code>struct S { int n; int* p; int a[2]; int* ap[2]; int xy[2][2]; }; void f() { S c, d; c = d; // equivalent to: c.n = d.n; c.p = d.p; c.a[0] = d.a[0]; // S::a is similar to your situation, only using c.a[1] = d.a[1]; // int instead of char. c.ap[0] = d.ap[0]; c.ap[1] = d.ap[1]; c.xy[0][0] = d.xy[0][0]; c.xy[0][1] = d.xy[0][1]; c.xy[1][0] = d.xy[1][0]; c.xy[1][1] = d.xy[1][1]; } </code></pre> <p>That I used int above doesn't change anything of the semantics, it works identically for char arrays, copying each char. This is the S::a situation in my code.</p> <p>Note that <em>p</em> and <em>ap</em> are copied shallowly (as is every other member). If those pointers "own" the memory to which they point, then it might not be safe. ("Safe" in your question is vague, and really depends on what you expect and how you handle things.)</p> <p>For an interesting twist, consider boost::shared_ptr and other smart pointers in C++. They can be copied shallowly, even though a deep copy is possible, and this can still be safe.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload