简体   繁体   中英

const_cast conversion to lvalue reference doesn't remove constness

I would like to understand a difference of the below two cases.

const uint32_t v0 = 0;
const uint32_t v1 = 1;

const_cast<uint32_t&>(v0) = v1;
std::cout << v0 << std::endl;

This results:

0

However,

struct S {
    const uint32_t v0;
    S() : v0( 0U ) {}
} s;

const_cast<uint32_t&>(s.v0) = v1;
std::cout << s.v0 << std::endl;

I get:

1

Regarding first case, why does "v0" remain 0?

Thanks in advance.

Applying const_cast on data and then modifying it which is actually constant has undefined behavior . The reason in that constant data may be placed in the readonly memory by the compiler. So trying to modify it will lead to UB , what output will be given depends on compiler.

Also as @Yakk pointed out, compiler may actually use only the value of the constant variable to reduce memory usage. In this case, any expression where the constant variable is involved is edited to replace the variable with actual value, so there is nothing in the memory. And if you try to change memory content, be prepared for BOOM .

Bottom Line: Don't do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM