For example:
https://godbolt.org/g/5eUkrx
void f(const int&);
void g1() {
const int i = 42;
if (i == 42) f(i);
if (i == 42) f(i);
}
void g2() {
int i = 42;
if (i == 42) f(i);
if (i == 42) f(i);
}
It seems like "f" mutating its argument should be UB, and therefore compilers should be allowed to assume it doesn't happen and optimize accordingly. Yet these two functions will produce different assembly.
I don't have a copy of the standard. Is this not guaranteed?
It's perfectly fine according to the standard to cast a pointer-to-const to pointer-to-non-const in C++ and then modify it (albeit it is confusing), as long the value the pointer points to wasn't declared as const
. In fact, C++ provides a keyword to do such a cast, const_cast
.
For instance, this is fine.
int a = 2;
const int* b = &a;
*const_cast<int*>(b) = 4;
But this isn't as a memory location to which pointer points to is const
.
const int a = 2;
const int* b = &a;
*const_cast<int*>(b) = 4;
Compiler in your example has to assume that a called function could possibly do that as it knows nothing about it, and prepare for such a situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With