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...
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...