tags:

views:

118

answers:

1

Can someone please explain me the following code snippet?

value struct ValueStruct {
    int x;
};

void SetValueOne(ValueStruct% ref) {
    ref.x = 1;
}

void SetValueTwo(ValueStruct ref) {
    ref.x = 2;
}

void SetValueThree(ValueStruct^ ref) {
    ref->x = 3;
}

ValueStruct^ first = gcnew ValueStruct;
first->x = 0;
SetValueOne(*first);

ValueStruct second;
second.x = 0;
SetValueTwo(second); // am I creating a copy or what? is this copy Disposable even though value types don't have destructors?

ValueStruct^ third = gcnew ValueStruct;
third->x = 0;
SetValueThree(third); // same as the first ?

And my second question is: is there any reason to have something like that?:

ref struct RefStruct {
    int x;
};

RefStruct% ref = *gcnew RefStruct;
// rather than:
// RefStruct^ ref = gcnew RefStruct;

// can I retrieve my handle from ref?
// RefStruct^ myref = ???

What is more: I see no difference between value type and ref type, since both can be pointed by handler ;(

+2  A: 
Ben Voigt
Are you sure that "RefStruct^ ref = gcnew RefStruct;" (where RefStruct is of reference type) puts a boxed value type instance on heap? And in the line above you have a mistake, did you mean *gcnew instead of ^gcnew?
MarcAndreson
Sorry, I use both C++/CLI and C# and late at night I focused on the *struct* part of `RefStruct` instead of the *ref* part. I'll fix my answer.
Ben Voigt
wow ;) ........
MarcAndreson
Ben Voigt