In my code I'm passing around some structures by reference, declaring them mutable and using the &
symbol. The problem is that in some place the fields are corrupted (happens only in release mode) and I don't know absolutely why.
I have found a fix, using ref keyword instead of the address-of operator. I understand that you can interchange them freely (in case of instance member parameters) but why did it fix my issue?
Here's a small code sample illustrating this:
[<Struct>]
type MyStruct =
val mutable private i : int
val mutable private f : float
new (a, b) = { i = a; f = b }
member t.I = t.i
member t.F = t.f
type Printer () =
member t.Print(data : MyStruct byref) = printfn "%d %f" data.I data.F
let bar (p : Printer) =
let mutable x = new MyStruct(2, 8.0)
p.Print(&x)
let foo (p : Printer) =
let mutable y = new MyStruct(2, 8.0)
p.Print(ref y) // What is exactly the difference, under the hood?
let main () =
foo (new Printer())
bar (new Printer())
do main ()
Passing structures with byref seems useful only for interop scenarios or if you want to mutate structure's fields. This is not my case however. Should I consider passing structure types by value instead (about 20 bytes or so)?
Thanks!