Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const cast and std launder

Tags:

c++

c++17

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;
}
like image 394
mkmostafa Avatar asked Apr 30 '26 16:04

mkmostafa


2 Answers

Yes. Attempting to modify a const object is UB, period.

like image 94
T.C. Avatar answered May 03 '26 06:05

T.C.


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.

like image 38
P.W Avatar answered May 03 '26 07:05

P.W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!