title: checking invariants in C++
body: <p>Are there any established patterns for checking class invariants in C++?</p>
  
  <p>Ideally, the invariants would be automatically checked at the beginning and at the end of each public member function. As far as I know, C with classes provided special <code>before</code> and <code>after</code> member functions, but unfortunately, design by contract wasn't quite popular at the time and nobody except Bjarne used that feature, so he removed it.</p>
  
  <p>Of course, manually inserting <code>check_invariants()</code> calls at the beginning and at the end of each public member function is tedious and error-prone. Since RAII is the weapon of choice to deal with exceptions, I came up with the following scheme of defining an invariance checker as the first local variable, and that invariance checker checks the invariants both at construction and destruction time:</p>
  
  <pre><code>template &lt;typename T&gt;
  class invariants_checker
  {
      const T* p;
  
  public:
  
      invariants_checker(const T* p) : p(p)
      {
          p-&gt;check_invariants();
      }
  
      ~invariants_checker()
      {
          p-&gt;check_invariants();
      }
  };
  
  void Foo::bar()
  {
      // class invariants checked by construction of _
      invariants_checker&lt;Foo&gt; _(this);
  
      // ... mutate the object
  
      // class invariants checked by destruction of _
  }
  </code></pre>
  
  <p>Question #0: I suppose there is no way to declare an unnamed local variable? :)</p>
  
  <p>We would still have to call <code>check_invariants()</code> manually at the end of the <code>Foo</code> constructor and at the beginning of the <code>Foo</code> destructor. However, many constructor bodies and destructor bodies are empty. In that case, could we use an <code>invariants_checker</code> as the last member?</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;stdexcept&gt;
  
  class Foo
  {
      std::string str;
      std::string::size_type cached_length;
      invariants_checker&lt;Foo&gt; _;
  
  public:
  
      Foo(const std::string&amp; str)
      : str(str), cached_length(str.length()), _(this) {}
  
      void check_invariants() const
      {
          if (str.length() != cached_length)
              throw std::logic_error("wrong cached length");
      }
  
      // ...
  };
  </code></pre>
  
  <p>Question #1: Is it valid to pass <code>this</code> to the <code>invariants_checker</code> constructor which immediately calls <code>check_invariants</code> via that pointer, even though the <code>Foo</code> object is still under construction?</p>
  
  <p>Question #2: Do you see any other problems with this approach? Can you improve it?</p>
  
  <p>Question #3: Is this approach new or well-known? Are there better solutions available?</p>