I have a program that uses boost::shared_ptr
s and, in particular, relies on the accuracy of the use_count
to perform optimizations.
For instance, imagine an addition operation with two argument pointers called lhs and rhs. Say they both have the type shared_ptr<Node>
. When it comes time to perform the addition, I'll check the use_count
, 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.
Because of this, I can never copy the shared_ptr
s without reason, i.e., every function takes the shared_ptr
s by reference or const reference to avoid distorting use_count
.
My question is this: I sometimes have a shared_ptr<T> &
that I want to cast to shared_ptr<T const> &
, but how can I do it without distorting the use count? static_pointer_cast
returns a new object rather than a reference. I'd be inclined to think that it would work to just cast the whole shared_ptr
, as in:
void f(shared_ptr<T> & x)
{
shared_ptr<T const> & x_ = *reinterpret_cast<shared_ptr<T const> *>(&x);
}
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?
Updating to Focus the Question
Critiquing the design does not help answer this post. There are two interesting questions to consider:
Is there any guarantee (by the writer of
boost::shared_ptr
, or by the standard, in the case ofstd::tr1::shared_ptr
) thatshared_ptr<T>
andshared_ptr<T const>
have identical layouts and behavior?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?