title: Why is writing to a non-const object after casting away const of pointer to that object not UB?
body: <p>According to the C++ Standard it's okay to cast away <code>const</code> from the pointer and write to the object if the object is not originally <code>const</code> itself. So that this:</p>
  <pre><code> const Type* object = new Type();
   const_cast&lt;Type*&gt;( object )-&gt;Modify();
  </code></pre>
  <p>is okay, but this:</p>
  <pre><code> const Type object;
   const_cast&lt;Type*&gt;( &amp;object )-&gt;Modify();
  </code></pre>
  <p>is UB.</p>
  <p><a href="https://stackoverflow.com/a/8356157/57428">The reasoning is</a> that when the object itself is <code>const</code> the compiler is allowed to optimize accesses to it, for example, not perform repeated reads because repeated reads make no sense on an object that doesn't change.</p>
  <p>The question is how would the compiler know which objects are actually <code>const</code>? For example, I have a function:</p>
  <pre><code>void function( const Type* object )
  {
      const_cast&lt;Type*&gt;( object )-&gt;Modify();
  }
  </code></pre>
  <p>and it is compiled into a static lib and the compiler has no idea for which objects it will be called.</p>
  <p>Now the calling code can do this:</p>
  <pre><code>Type* object = new Type();
  function( object );
  </code></pre>
  <p>and it will be fine, or it can do this:</p>
  <pre><code>const Type object;
  function( &amp;object );
  </code></pre>
  <p>and it will be undefined behavior.</p>
  <p>How is compiler supposed to adhere to such requirements? How is it supposed to make the former work without making the latter work?</p>