Deep copy of struct

  • Thread starter Thread starter Miljana Murgas
  • Start date Start date
M

Miljana Murgas

I have a struct like this:
public struct Vec
{
public float[] m;
public Vec(float v1, float v2)
{
m = new float[2];
m[0]=v1;
m[1]=v2;
}

public Vec operator+(Vec v1, Vec v2)
{
Vec r = new Vec(0,0);
r.m[0] = v1[0]+v2[0];
r.m[1] = v1[1]+v2[1];
return r;
}
}

Then I try something like this:
Vec v1 = new Vec(1,1);
Vec v2 = new Vec(2,2);
Vec v3 = v1 + v2;
v3.m[0] =0; // v1.m[0] is still 1, v2.m[0] is still 2

however, when trying something like:
Vec v1 = new Vec(1,1);
Vec v3 = v1;
v3.m[0] = 0; // v1.m[0] is 0!!!

In first case, + operator creates new object with new "m" array, so changes
in v3 doesn`t affect v1 or v2... In second case, shalow copy is performed,
so v1 and v3 share same "m" array... Question is, how do I create deep copy
of struct, so I can use assignment operator (=)? I could use copy
constructor, but then I will have to write:
Vec v3 = new Vec(v1);
which is ugly...
 
Miljana Murgas said:
I have a struct like this:

<snip>

You've basically given a good example of why mutable structs should be
avoided - and in particular why structs which contain *mutable
reference types (such as arrays)* should be avoided. I suggest you make
it immutable, with any calls which *would* change the contents actually
just returning a new one.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top