Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You are only allowed to cast away constness of an object which is known <strong>not</strong> to be <code>const</code>. For example, an interface may pass objects through using a <code>const</code> pointer or a <code>const</code> reference but you passed in an object which isn't <code>const</code> and want/need to modify it. In this case it may be right thing to cast away constness.</p> <p>On the other hand, casting away constness of an object which was <code>const</code> all the way can land you in deep trouble: when accessing this object, in particular when writing to it, the system may cause all kinds of strange things: the behavior is not defined (by the C++ standard) and on a particular system it may cause e.g. an access violation (because the address of the object is arranged to be in a read-only area).</p> <p>Note that despite another response I saw <code>const</code> objects need to get an address assigned if the address is ever taken and used in some way. In your code the <code>const_cast&lt;int&amp;&gt;(maxint)</code> expression essentially obtains the address of your constant int which is apparently stored in a memory area which is marked to be read-only. The interesting aspect of your code snippet is that it is like to <strong>apparently</strong> work, especially when turning on optimization: the code is simple enough that the compiler can tell that the changed location isn't really used and doesn't actually attempt to change the memory location! In this case, no access violation is reported. This is what apparently is the case when the constant is declared inside the function (although the constant may also be located on the stack which typically can't be marked as read-only). Another potential outcome of your code is (independent of whether the constant is declared inside the function or not) is that is actually changed and sometimes read as 100 and in other contexts (which in some way or another involve the address) as 200.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload