|
|
|
|
|
by codeflo
1608 days ago
|
|
I don’t think so. According to https://stackoverflow.com/a/39382728 (the original SO answer that prompted the linked SO question, and which quotes the relevant parts of the spec), the allocation is not UB, but accessing the member after that (at least without the std::launder trick) is UB. It’s precisely this latter part that I don’t think is very reasonable to have in the spec. |
|
As for why the spec prohibits the modification of const values: one of the reasons for compilers being allowed to treat const values as being truly immutable is for performance. If the compiler can see the actual value then it can avoid the memory read entirely, and if it doesn't know the actual value then it only needs to do one memory read.
If those const values could change without the compiler being aware then it now needs to do an awful lot more fetching from memory as it cannot guarantee that the value did not change. Some of it could be optimized away, but it would still make code a lot slower if - for example: mixing reads from const ints with pointer/reference manipulation of ints - as due to potential aliasing the compiler would likely have to read those const ints from memory each time.