I have a struct that contains a field which is a handle to something else.
I use this handle to keep the resource from being dropped, but my code does not use that field.
But I found that in the release build, this field is optimized away by the compiler. What's the recommended way to resolve this?
Why would you keep data you don't use?
Or are you using it but not telling compiler you use it?
If you use it, you need to tell compiler this. Easy they to do it, would be to move data into struct and get reference to it from struct. So, you will tell compiler you are using it.
I don't think the compiler is allowed to optimize away unused field . Are you sure that's what happening? What evidence you saw make you think it's doing that?
If your code does not use that field then who does? I can only think that it is code in some other language or a hardware device.
In either case that "something else" needs to know where the field is within your struct. Even if the compiler did not optimize the field away it could reorder the fields in the structs memory layout. Sounds like you need to treat that struct as part of a foreign function interface and have #[repr(C)]
on that struct.
Sorry to bother you guys. I can't reproduce it with a simple test like this. playground
Then it must be my problem.
It depends what you mean by the field keeping something else alive.
The compiler will not optimize away types that have Drop
. For unused simple copy types it should be impossible to observe whether they're there or not.
There's no garbage collector in Rust, so non-owning pointers and references don't keep anything alive, whether they're in a struct or not.
The compiler may reorder fields of structs. If some code relies on the field being there, set #[repr(c)]
on the struct.