title: Can I cast shared_ptr<T> & to shared_ptr<T const> & without changing use_count?
body: <p>I have a program that uses <code>boost::shared_ptr</code>s and, in particular, relies on the accuracy of the <code>use_count</code> to perform optimizations.</p>
  
  <p>For instance, imagine an addition operation with two argument pointers called lhs and rhs.  Say they both have the type <code>shared_ptr&lt;Node&gt;</code>.  When it comes time to perform the addition, I'll check the <code>use_count</code>, and if I find that one of the arguments has a reference count of exactly one, then I'll reuse it to perform the operation in place.  If neither argument can be reused, I must allocate a new data buffer and perform the operation out-of-place.  I'm dealing with enormous data structures, so the in-place optimization is very beneficial.</p>
  
  <p>Because of this, I can never copy the <code>shared_ptr</code>s without reason, i.e., every function takes the <code>shared_ptr</code>s by reference or const reference to avoid distorting <code>use_count</code>.</p>
  
  <p>My question is this: I sometimes have a <code>shared_ptr&lt;T&gt; &amp;</code> that I want to cast to <code>shared_ptr&lt;T const&gt; &amp;</code>, but how can I do it without distorting the use count?  <code>static_pointer_cast</code> returns a new object rather than a reference.  I'd be inclined to think that it would work to just cast the whole <code>shared_ptr</code>, as in:</p>
  
  <pre><code>void f(shared_ptr&lt;T&gt; &amp; x)
  {
    shared_ptr&lt;T const&gt; &amp; x_ = *reinterpret_cast&lt;shared_ptr&lt;T const&gt; *&gt;(&amp;x);
  }
  </code></pre>
  
  <p>I highly doubt this complies with the standard, but, as I said, it will probably work.  Is there a way to do this that's guaranteed safe and correct?</p>
  
  <p><strong>Updating to Focus the Question</strong></p>
  
  <p>Critiquing the design does not help answer this post.  There are two interesting questions to consider:</p>
  
  <ol>
  <li><p>Is there any guarantee (by the writer of <code>boost::shared_ptr</code>, or by the standard, in the case of <code>std::tr1::shared_ptr</code>) that <code>shared_ptr&lt;T&gt;</code> and <code>shared_ptr&lt;T const&gt;</code> have identical layouts and behavior?</p></li>
  <li><p>If (1) is true, then is the above a legal use of reinterpret_cast?  I think you would be hard-pressed to find a compiler that generates failing code for the above example, but that doesn't mean it's legal.  Whatever your answer, can you find support for it in the C++ standard?</p></li>
  </ol>