RE: [Boost-users] Re: Conversions between shared_ptr<Base>andshared_ptr<Derived>

Konstantin Baumann
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
(*this); } template<class S> operator const shared_ptr<S>&() throw() const { BOOST_STATIC_ASSERT(T* is convertible to S*); return reinterpret_cast
(*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*.
participants (1)
-
Ben Hutchings