To explain why the compiler has to do "all or nothing" when it comes to where to store the struct
: In most processors, memory pages are 4KB (a few has 8KB pages). That is the granularity of "read only" vs "read/write" memory blocks. So you can't have one 4-byte integer in read-only memory, and then the next 4 byte integer in read-write memory (unless they are exactly straddling a 4KB memory boundary - but that would definitely make for quite wasteful use of memory if you have an array of 3000 of them, taking up 12MB).
Note that this is not an "optimisation". Read-only memory is not faster than read-write memory. It's a protection against users being silly with const
and writing to the data they shouldn't write to.
Also if you add a constructor that "does something" to your struct
, it will most likely store the struct in read-write memory, because it's quite tricky for the compiler to generate code to switch read-only on and off at runtime.