Modifying a const constructed object after a const_cast is UB (I believe due to constant propagation). Is it still UB even when combined with std::launder (which AFAIK prevents some optimizations such as const propagation)?
#include <new>
#include <iostream>
struct C
{
int i;
};
int main(const int argc, const char * const * const argv)
{
const C c{1};
auto x = std::launder(const_cast<C*>(&c));
++x->i;
std::cout << x->i << std::endl;
std::cout << c.i << std::endl;
return 0;
}
Yes. Attempting to modify a const object is UB, period.
const object - an object whose type is const-qualified, or a non-mutable subobject of a const object. Such object cannot be modified: attempt to do so directly is a compile-time error, and attempt to do so indirectly (e.g., by modifying the const object through a reference or pointer to non-const type) results in undefined behavior.
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