Templated Smart Pointer - Implicit Casting?

Started by
11 comments, last by Desert Fox 18 years, 10 months ago
This thread where someone mentioned that smart pointers and casting is impossible. They were corrected - I cast my smart pointers all the time. The unfortunate thing is they can't be implicitly casted. I was also discussing this very thing the other night. Anyway. What I want to know, take your standard, every day shared-pointer style implementation of a smart pointer using templates. Is there a sensible way to allow the pointer to be implicitly cast like a normal pointer is? For reference, here is some code from my own pointer. It's just showing the relevent details of how I implement casting. The cast function will cause an implicit conversion (and will generate nice compilation errors if it is an illegal conversion).
template <class T>
class ASharedPtr
{
    T* ptr;
    size_t* count;
public:
    // various constructors:
    ASharedPtr() : ptr(0), count(new size_t(1)) {}
    ASharedPtr(const ASharedPtr& s) : ptr(s.ptr), count(s.count) {++(*count);}
    explicit ASharedPtr(T* p) : ptr(p), count(new size_t(1)) {}
    ASharedPtr(T* p, size_t* pcount) : ptr(p), count(pcount) {assert(count); ++(*count);}

    template <class U>
    ASharedPtr<U> Cast() { return ASharedPtr<U>(ptr, count); }
};
The idea I'm trying to get at is:
// some classes:
class CBase {};
class CChild : public CBase {};

// make some pointers
CChild* rawptr = new CChild;
ASharedPtr<CChild> smartptr(new CChild);

// Some functions
void DoStuffRaw(CBase* x);
void DoStuffSmart(const ASharedPtr<CBase>& x);

// The raw pointer is cast implicitly
DoStuffRaw(rawptr);
// The smart pointer can't
DoStuffSmart(smartptr); // <- error!

// The smart pointer must do this instead
DoStuffSmart(smartptr.Cast<CBase>());
Any sensible way to make the line marked as "error" actually work?
Advertisement
Try something like

#include <boost/utility.hpp>#include <boost/type_traits.hpp>using boost::enable_if;using boost::is_base_and_derived;template <class T>class ASharedPtr{public:   template<class U>    ASharedPtr( const AsharedPtr<U>& rhs,               typename enable_if< is_base_and_derived<T,U> >::type* dummy = 0 )   : ptr(s.ptr), count(s.count)    {      ++(*count);   }   /* more crap */};


(blah, bugs)
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Ooooh, clever [smile] Danke.

(boost to the rescue!)
You ought to check the compiler regression test look for boost::is_base_or_derived, if it works anything like the Loki equivalent, is it not easy to make it work on most compilers.
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Andrew - Look at the code that's there now, I've finally checked it on GCC 4, and fixed my errors :)
MKH - good point
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Why not implement some cast operators? Works perfectly for me...

template
class SmartPointer
{
.... usual stuff here...
inline _T* operator -> () const
{
return ptr;
}

inline _T& operator * () const
{
return *ptr;
}

inline operator _T* () const
{
return ptr;
}
private:
_T *ptr;
}
Because implicit conversion operators unveil a slew of small but subtle problems. It's very easy for the pointer to "escape" from the smart pointer, which can mess up your reference count (someone writes a function/class that takes a raw pointer and then holds onto it, if you pass this entity a smart pointer it will still accept it due to the conversion, but now the ref count is borked). And, it's easily possible to do a "delete sp", which due to the implicit conversion, will result in your pointer being deleted(!). That is why most smart pointers provide an explicit conversion to the raw underlying type; yes, it's still possible to do the things mentioned above, but it's much more obvious that they are being done.

And Fruny, is the if_base_and_derived test really neccesary? Shouldn't implicit pointer conversion rules essentially take care of the conversion issue (though granted, using it doesn't hurt and ensures a little more type safety, as I guess T could be something like void*)
"Is life so dear, or peace so sweet, as to be purchased at the price of chains and slavery?" - Patrick Henry
Correct me if I'm wrong, but don't the boost smart pointers do this?

#include <boost/smart_ptr.hpp>using namespace boost;class A {};class B : public A {};void smart_by_value( shared_ptr< A > a ) {}void smart_by_const_ref( const shared_ptr< A > & a ) {}int main ( int argc , char ** argv ){	shared_ptr< B > b ( new B ) ;	shared_ptr< A > a ( b ) ; //implicit cast?	smart_by_value( b ); //implicit cast?	smart_by_const_ref( b ); //implicit cast?}


I think boost handles this by having templatized constructors... it's been awhile since I've looked at the source though.

EDIT: Yup, checked the 1.32 source:
    template<class Y>    shared_ptr(shared_ptr<Y> const & r): px(r.px), pn(r.pn) // never throws    {    }
Fruny: What's the purpouse of the enable_if in your example? More precise error if the pointer can't be cast (read: Y is neither T nor derived from T)?

[Edited by - MaulingMonkey on May 26, 2005 7:22:15 AM]
Woah. You're right - without the enable_if business, it should still generate the appropriate errors if the conversion is not possible.
Quote:Original post by Anonymous Poster
Why not implement some cast operators? Works perfectly for me...


As somebody already mentioned, implicit casting via overloading cast operators can lead to unforeseen subtle issues which can cause headaches to fix. That is why std::basic_string does not overload cast operator to implicitly convert to C style string but instead make it explicit via c_str method.

Generally prefer conversion constructors and/or explicit conversion via named methods as it states your intent, just the reason why the family of C++ cast operators are ugly. They explicitly state your intent, and easy to find.

This topic is closed to new replies.

Advertisement