Can't find anything about this but if I find code like this
fixed(Foo* foo=bar) {
doSomething(bar); // not foo
}
where foo isn't referenced, can I be certain that bar is kept fixed within the region and not gone due to optimization?
Yes. That's the whole point of the fixed
statement, as also noted in the specification:
For each address computed by a fixed-pointer-initializer the fixed statement ensures that the variable referenced by the address is not subject to relocation or disposal by the garbage collector for the duration of the fixed statement. For example, if the address computed by a fixed-pointer-initializer references a field of an object or an element of an array instance, the fixed statement guarantees that the containing object instance is not relocated or disposed of during the lifetime of the statement.
In your case, the fixed-pointer-initializer is bar
. For grammar reasons, the declaration of foo
is needed, however. That's probably the reason for this idiom where the array bar
has to be unmovable, but you don't really need the pointer.
One side note: It's not optimization that can move bar
away from it's memory location outside of such a fixed
statement. It's the garbage collector compacting the heap to ensure that it's no longer fragmented. I wouldn't call that an optimization, though.