title: Figuring out the constness of an object within its destructor
body: <p>I have a class Stuff, with two functions foo (const and non-const):</p>
  
  <pre><code>class Stuff
  {
  public:
      ~Stuff() { foo(); }
  
      void foo() const { cout &lt;&lt; "const foo" &lt;&lt; endl; }
      void foo()       { cout &lt;&lt; "non-const foo" &lt;&lt; endl; }
  };
  </code></pre>
  
  <p>Here's what I am trying to do:</p>
  
  <ol>
  <li><p>If the stuff was const, call const foo in the destructor of Stuff.</p></li>
  <li><p>if the stuff wasn't const, call non-const foo in the destructor of Stuff.</p></li>
  </ol>
  
  <p>I was hoping that just defining the destructor as shown above would work, but it turns out that the constness is stripped away right before executing the destructor (it is enforced right after the constructor completes, so I cannot set any flag there either). To make it clearer, here's an example:</p>
  
  <pre><code>{ Stuff stuff; }
  { const Stuff cstuff; }
  </code></pre>
  
  <p>This code prints "non-const foo" twice. I want it to print "non-const foo", followed by "const foo". Is that possible with C++?</p>
  
  <p>EDIT: A few people are asking for more context. In the real code, stuff is basically a handle to some data. If stuff is accessed in a non-const manner, I assume that the data has been modified, so I need to communicate that to other processes (MPI) using the foo function (after I am done modifying it -> in the destructor, when I release the handle). If it was accessed in a const-manner, I know I don't need to transfer anything, so I am calling non-const foo, that does nothing. </p>