Boost logo

Boost Users :

From: Ben Hutchings (ben.hutchings_at_[hidden])
Date: 2004-02-11 10:55:11


Konstantin Baumann <boost_at_[hidden]> wrote:
> For performance reasons I would like to see something like the
> following conversion operators in shared_ptr<T>:
>
> template<class T>
> class shared_ptr {
> public:
> ...
> template<class S>
> operator shared_ptr<S>&() throw() {
> BOOST_STATIC_ASSERT(T* is convertible to S*);
> return reinterpret_cast<shared_ptr<S>&>(*this);
> }
>
> template<class S>
> operator const shared_ptr<S>&() throw() const {
> BOOST_STATIC_ASSERT(T* is convertible to S*);
> return reinterpret_cast<const shared_ptr<S>&>(*this);
> }
>
> }; // class shared_ptr<T>
>
> This would mimic the standard conversion from T* to S* without any
> performance penalty for shared_ptr<T>.
<snip>

Don't sacrifice correctness for performance. First, the
reinterpret_cast results in undefined behaviour. If you think you
know that the actual behaviour is OK, you are wrong. If S is a base
class of T then the conversion of T* to S* generally requires
changing the bits of the pointer, unless S is the first non-virtual
base. Second, if we can create a reference of type shared_ptr<S> to
an object of type shared_ptr<T>, then we can also modify that object
to contain a pointer of type S* which may not be convertible to T*.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net