title: Can a member variable (attribute) reside in a register in C++?
body: <p>A local variable (say an int) can be stored in a processor register, at least as long as its address is not needed anywhere. Consider a function computing something, say, a complicated hash:</p>
  
  <pre><code>int foo(int const* buffer, int size)
  {
      int a;   // local variable
      // perform heavy computations involving frequent reads and writes to a
      return a;
  }
  </code></pre>
  
  <p>Now assume that the buffer does not fit into memory. We write a class for computing the hash from chunks of data, calling <code>foo</code> multiple times:</p>
  
  <pre><code>struct A
  {
      void foo(int const* buffer, int size)
      {
          // perform heavy computations involving frequent reads and writes to a
      }
  
      int a;
  };
  
  A object;
  while (...more data...)
  {
      A.foo(buffer, size);
  }
  // do something with object.a
  </code></pre>
  
  <p>The example may be a bit contrived. The important difference here is that <code>a</code> was a local variable in the free function and now is a member variable of the object, so the state is preserved across multiple calls.</p>
  
  <p>Now the question: would it be legal for the compiler to load <code>a</code> at the beginning of the <code>foo</code> method into a register and store it back at the end? In effect this would mean that a second thread monitoring the object could never observe an intermediate value of <code>a</code> (synchronization and undefined behavior aside). Provided that speed is a major design goal of C++, this seems to be reasonable behavior. Is there anything in the standard that would keep a compiler from doing this? If no, do compilers actually do this? In other words, can we expect a (possibly small) performance penalty for using a member variable, aside from loading and storing it once at the beginning and the end of the function?</p>
  
  <p>As far as I know, the C++ language itself does not even specify what a register is. However, I think that the question is clear anyway. Whereever this matters, I appreciate answers for a standard x86 or x64 architecture.</p>