471,612 Members | 2,506 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,612 software developers and data experts.

Deep copy of struct

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...
Nov 25 '05 #1
1 3325
Miljana Murgas <mi*****@hotmail.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 26 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Ace Alexander | last post: by
5 posts views Thread by Tony Johansson | last post: by
25 posts views Thread by Justin Robbs | last post: by
5 posts views Thread by marcosegurini | last post: by
5 posts views Thread by BenW | last post: by
26 posts views Thread by saxenavaibhav17 | last post: by
3 posts views Thread by bob | last post: by
1 post views Thread by XIAOLAOHU | last post: by
reply views Thread by leo001 | last post: by
1 post views Thread by ZEDKYRIE | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.