Sign in to follow this  
Andrew Russell

Unity Templated Smart Pointer - Implicit Casting?

Recommended Posts

Andrew Russell    1394
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?

Share this post


Link to post
Share on other sites
Fruny    1658
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)

Share this post


Link to post
Share on other sites
Fruny    1658
Andrew - Look at the code that's there now, I've finally checked it on GCC 4, and fixed my errors :)
MKH - good point

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
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;
}

Share this post


Link to post
Share on other sites
Desert Fox    277
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*)

Share this post


Link to post
Share on other sites
MaulingMonkey    1728
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]

Share this post


Link to post
Share on other sites
snk_kid    1312
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.

Share this post


Link to post
Share on other sites
Fruny    1658
I'd put an enable_if because I wasn't thinking about the implementation of the class, I just wanted to disable conversion from X<A> to X< B> if A didn't derive to B. It's true that without it you'll still get an error, but (*clings desperately to the notion that he is right*) it will come from the class's internals rather than being a "can't convert X<A> to X< B>" error.

[Edited by - Fruny on May 26, 2005 9:50:39 AM]

Share this post


Link to post
Share on other sites
MaulingMonkey    1728
Fruny: Ahh, okay :-).

GCC 3.4.2 at least seems to grok a templatized conversion-to-another-shared_ptr operator as well, which some may find preferable. Example bellow includes errors as reported when attempting an invalid upcast:

//#include <boost/shared_ptr.hpp>
//using namespace boost;

template < typename T >
struct shared_ptr
{
T * pointer;
public:
explicit shared_ptr( T * pointer )
: pointer( pointer )
{
}
shared_ptr( const shared_ptr & other )
: pointer( other.pointer )
{
}

template < typename downcast_t >
operator shared_ptr< downcast_t > ( void ) const
{
//../main.cc:21: error: invalid conversion from `A* const' to `B*'
//../main.cc:21: error: initializing argument 1 of `shared_ptr<T>::shared_ptr(T*) [with T = B]'
return shared_ptr< downcast_t >( pointer ); //line 21
}
};

class A{};
class B : public A {};

int main ( int argc , char ** argv )
{
shared_ptr< B > b ( new B );
shared_ptr< A > a ( b );
shared_ptr< B > b2( a ); //../main.cc:32: instantiated from here
}




Following this idea, we can take this:
template <class U>
ASharedPtr<U> Cast() { return ASharedPtr<U>(ptr, count); }
And go like this:
template <class U>
operator ASharedPtr<U> Cast() const { return ASharedPtr<U>(ptr, count); }
And implicit casts should then work :-). Seems blatently obvious in hindsight, why didn't I think of that first ^_^.

Edit: <U> -> &lt;U&gt; escaping... bad underlines, no biscuts!!!

[Edited by - MaulingMonkey on May 26, 2005 9:23:16 AM]

Share this post


Link to post
Share on other sites
Desert Fox    277
I guess there's nothing *wrong* with that implicit conversion approach. I still prefer to perform the conversion in the constructor however, especially since it eliminates the need to pass the reference count pointer as a parameter to the constructor:


template <class U>
ASharedPtr(const ASharedPtr<U>& other)
: ptr_(other.ptr_), count_(other.count_) {++*count_;}



Note that you can also put an explicit in there and force the user to perform essentially an explicit cast to do the conversion

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this