title: C++ Const-correctness with volatile and external data acess
body: <p>I'm an embedded C developer who has recently started messing with C++ code on an embedded device and am unsure about how const-correctness applies when a class accesses volatile data such as memory-mapped registers or data on an external device, such as an Analog-to-Digital Converter (ADC).</p>
  
  <p>For example, I have classes that interface to the device's hardware modules by accessing its memory-mapped registers through a pointer, like so:</p>
  
  <pre><code>class IOPin
  {
  public:
      /* Constructor, destructor, other methods...*/
  
      // should this be a const method?
      bool ReadIOState() {return portregs_-&gt;state;}
  
  private:
      /* Other private stuff...*/
  
      // Constructor points this to the right set of memory-mapped registers
      volatile struct portregs_t
      {
          uint32_t control;
          uint32_t state;
          uint32_t someotherreg;
      } *portregs_;
  };
  </code></pre>
  
  <p>The register names are of course made up for the sake of example.  I'm using a Microchip PIC32 device for anyone who's curious.</p>
  
  <p>From my possibly incorrect understanding, marking a method <code>const</code> means that the observable state of the object should not change as far as the caller is concerned.  So should the <code>ReadIOState()</code> method <em>not</em> be <code>const</code> because it accesses <code>volatile</code> data that could change at any time and thus the caller would observe the change?  Or should it be <code>const</code> because the <em>method</em> isn't explicitly changing anything?</p>
  
  <p>Currently, I am leaning towards not making that method <code>const</code> for the reason stated in the question.  This is especially true after stumbling upon <a href="http://herbsutter.com/2013/05/24/gotw-6a-const-correctness-part-1-3/" rel="nofollow noreferrer">this GotW article</a>, which states that the meaning of <code>const</code> is changing to mean "able to read concurrently".  My embedded application is single-threaded, but I suppose that could be a good litmus test for <code>const</code>ness in general.</p>
  
  <p>Also, how does the compiler treat <code>const</code> methods?  That is, what happens when I want to poll the state of the IO like this:</p>
  
  <pre><code>// wait for IO pin to go high
  while(!myIOpin.ReadIOState())
  {}
  </code></pre>
  
  <p>If <code>ReadIOState()</code> is <code>const</code>, then can the compiler reuse the value returned after one call or is it smart enough to see that it is accessing <code>volatile</code> data and not do that?</p>