Unity Templated Smart Pointer - Implicit Casting?

Recommended Posts

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 on other sites
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 on other sites
Ooooh, clever [smile] Danke.

(boost to the rescue!)

Share on other sites
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.

Share on other sites
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 on other sites
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 on other sites
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 on other sites
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 on other sites
Woah. You're right - without the enable_if business, it should still generate the appropriate errors if the conversion is not possible.

Share on other sites
Quote:
 Original post by Anonymous PosterWhy 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 on other sites
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 on other sites
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 on other sites
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

Create an account

Register a new account

• Forum Statistics

• Total Topics
627708
• Total Posts
2978732
• Similar Content

•
I'm looking for a team to help me out with a 3D platformer. Basically, you jump between platforms with parkour elements and you fight enemies with a mix of melee and ranged attacks. This is purely a hobby project. I'm not promising any payment, ever. You can do it for experience, to learn, for fun, whatever, as long as you don't expect to get paid. Right now I need a 3D modeler and animator. Reply or email me at jordestoj@yahoo.com if you're interested. Thanks.

• Hi all!
We are looking for a C# programmer for our 2D Action RPG titled Adavia, made in Unity.
The game itself is akin to Legend of Zelda: Link to the Past, though we're also adding in traditional RPG elements such as Character Creation.
This is more of a hobby than anything commercial, if it somehow does manage to go commercially, all revenue will be split equally among the team.
If you're interested, we ask that you be comfortable with:
Unity Coding A.I's for enemies and NPCs. Working with GUI's. Communicating regularly with the team via Skype (text only). If you have any questions or would like to apply, please contact me at nathan.jenkins1012@gmail.com

• I'm the co-director of LM Team, a 7-member team currently constructing a fangame based upon the Mega Man series. We've been working for about 2 years now, and both of our current programmers are busy for the next 6 months or so. Because of this, we're currently looking for a programmer (or more) to take care of gameplay and animation programming. We already have a base system in place that may optionally be built upon. This will be a hobby project to invest your free time in, not a gamedev gig.
We're currently about 67% done with the OST, 75% done with the design work, and 33% done with the graphical work. As such, the specifications of what we need should remain pretty stagnant from now on.
Here's some links of our team's work, to give you an idea of what we're currently capable of achieving:
Actual Y+1 Stuff:
- Current public playlist of music
- Old footage of the first boss of the game, since been altered slightly based on feedback
- Mockups
m9m (director, composer):

- Grand Dad Reboot - Ominous Cavern
- Lands of Onlup
- Mega Man Revolution Remix - Wily 2
MrKyurem (co-director, main designer, me):
- Boil Man - 10th place in Make a Good Mega Man Level 2 Contest
NaOH (programmer [not programmer who is currently working on the engine]):
- Programmer for Make a Good Mega Man Level 2 Contest's release game (did co-op mode and leaderboard functionality)
- 15 years of programming experience
- Castlevania 3 controls romhack
- GML code beautifier
- Beat-Em-Up engine
Alm (artist):
- Cutscene for a personal project
- Tileset for Boil Man's stage in MaGMML2
- Concept sprite
Valo (artist):
- Jungle Man tileset in Mega Man SD
- Boxart for Mega Man SD
- Wily sprite
Karakato (artist):
- Robot Masters in BCA
- Idol Woman
- Stage Select for separate project
Deathro (composer):
- Through the Eye of a Prism - 2nd place in Famicompo 2015's Original category
- Mega Man SFR - Wily 2
- Geno Force - Silent Breeze
Contact
If you're interested in joining, I'd recommend signing up to Discord, as we almost exclusively communicate through this.
Discord Tags:
MrKyurem#8741
m9m#1104
Email:
LMTeam.Y1@gmail.com

• You are the commander of a special forces squadron. You were given a task that appeared simple at first glance - to check for suspicious activity in the building of an abandoned psychiatric hospital. But you could not even imagine what you will actually have to face.

• You find yourself in an abandoned place full of mutants in the dead of night, and have to kill waves of monsters with a different kind of weapon. The main goal is to survive through the night.
Controls:
WASD – Walk
Shift – Run
Mouse1 - Attack
Space - Jump
Scroll Down – Change weapon
Esc - Exit, pause