Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code> const int i0 = 5; //int i1 = const_cast&lt;int&gt;(i0); // compilation error int i2 = (int)i0; // okay int i3 = 5; //const int i4 = const_cast&lt;const int&gt;(i3); // compilation error const int i5 = (const int)i3; // okay </code></pre> <p>The compilation errors are caused because you don't cast const away/add const. Instead, you copy i0. For that operation, no cast is required at all:</p> <pre><code>int i1 = i0; const int i4 = i3; </code></pre> <p>The type you cast to should actually be a pointer or reference. Otherwise, using const_cast doesn't make sense since you could straight copy it. For pointers, for example, you can cast away the const, because dereferencing the pointer will yield another type for a <code>const T*</code> (yields <code>const T</code>) than for a <code>T*</code> (yields <code>T</code>). For references, the same is true: <code>T&amp;</code> will access the object using another <em>this</em> pointer type than using <code>const T&amp;</code>. Now what you really wanted to archive:</p> <pre><code> const int i0 = 5; //int &amp; i1 = const_cast&lt;int&amp;&gt;(i0); // okay (but dangerous) int &amp; i2 = (int&amp;)i0; // okay (but dangerous) int i3 = 5; //const int&amp;i4 = const_cast&lt;const int&amp;&gt;(i3); // ok now and valid! const int&amp;i5 = (const int&amp;)i3; // okay too! </code></pre> <p>The above can lead to undefined behavior, when you write to an originally const object through a reference to non-const (actually, merely casting and reading it isn't undefined behavior in itself. But if you're casting away const, you may also write to it, which then yields the undefined behavior)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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