(Not) Storing non-Copy types in volatile memory

I'm exploring unsafe embedded programming world and I came across pointer volatile operations like std::ptr::read_volatile and std::ptr::write_volatile. As I figured out, they are mainly intended to use in embedded programming (memory-mapped IO).

However, safety section of read_volatile says:

However, storing non-Copy types in volatile memory is almost certainly incorrect.

But why? Is it because embedded systems will likely memory-map primitive-like values like booleans, u8s, etc?

Non-Copy types are types that shouldn't be duplicated, because (unless they are non-Copy only for compatibility with future versions) they represent control over something unique — a memory allocation or something else. Volatility implies that the memory might change in ways that would cause duplication or forgetting, which would likely violate the invariants of the non-Copy type.

Therefore, the cases where reading a value of a non-Copy type is sound, because the value you are reading is not being disturbed, are also typically cases where you could use std::ptr::read instead.

But there could possibly be some particular circumstance in which this is sound, so the documentation just says “almost certainly”.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.