简体   繁体   中英

const_cast c++ did not work for me

trying to understand the usage of const_cast. Code like the following:

const char* text="bb";
(const_cast<char&>(*text))='a';
cout<<*text;

...generates a runtime error.

Another question, in memory, how does the runtime (it) know that this area is const or not, what kind of flag is this ?

That code invokes undefined behaviour ; it is not valid to write to a string literal (nor indeed to any const object).

The C++ standard does not define how this should fail (or even that it must fail). But on a typical platform, it will be up to the OS and the underlying hardware to detect the problem. The storage for "bb" will typically be in a dedicated section of the executable, which is marked as read-only. See eg http://en.wikipedia.org/wiki/Memory_protection .

However, there are uses of const_cast that don't invoke undefined behaviour. eg:

int x = 5;  // Not a const object

const int *p = &x;

int *q = const_cast<int *>(p);

*q = 6;  // This is ok

The string might be put in static memory. So it is an undefined behaviour. Try this

char t[]="bb";
const char* text = t;
(const_cast<char&>(*text))='a';
cout<<*text;

You can only const_cast something which you know is not really const. In this case, even if text is const, we know that it points to t which is not const. Hence we can safely cast away the const.

Generally speaking, the run-time doesn't know whether a particular variable is actually const . If you cast away const -ness, you get undefined behavior if you end up writing to a variable defined as const (as opposed to a normal variable to which you happen to have a const pointer/reference).

If they wanted to mandate that the run-time "know" about things being const , then they'd probably prescribe specific behavior (eg, throwing a particular exception) when/if you write to a const variable. Some systems would support that quite easily -- but others wouldn't, so a specific response isn't required.

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