Sign in to follow this  

Unity Templated Smart Pointer - Implicit Casting?

This topic is 4582 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


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

This topic is 4582 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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  

  • Forum Statistics

    • Total Topics
      628642
    • Total Posts
      2983993
  • Similar Content

    • By arash khalaqhdoust
      hey guys i hope you doing all well. last night i released my first game in google app store, i really appreciate you guys  to download it. and share your reviews about it
      the idea of game comes from mini hackgame of Bioshock.
       link of download:
      https://play.google.com/store/apps/details?id=com.RVBinary.piperist
      many thanks
    • By ForgedInteractive
      Who We Are
      We are Forged Interactive, a small team of like-minded game developers with the sole purpose of making games we love! Currently, we're progressing very quickly with our first project and there are plenty of opportunities and work for new interested programmers. With this project, our development platform is Unity 5.5.2 and C# as our behavioral language. Since this project is our first release, the game itself is a smaller project though progress is moving quickly. We are looking to finalize the current project and get started on future projects in the near future and are expanding our team to do so.
       
      Who We Are Looking For:
      Programmer Level Designer  
      About the Game
      Ours is the tale of two siblings, thrown into a world of chaos. Living in the shadow of their parents' heroic deeds and their Uncle's colorful military career, Finn and Atia are about to become the next force to shape our world. How will you rise through the ranks of Hereilla and what will be your legacy? Once defeated your enemies turn coat and join you in your adventures. Players can enjoy a range of troops and abilities based on their gameplay style which become more important as maps introduce more challenging terrain, enemies and bosses. Strong orc knights, dangerous shamans, and even a dragon are out on the prowl. Knowing when to fight and when to run, and how to manage your army is essential. Your actions alone decide the fate of this world.
       
      Previous Work by Team
      Although we are working towards our first game as Forged Interactive, our team members themselves have worked on titles including and not limited to:
      Final Fantasy Kingsglaive FIFA 2017 Xcom 2 Civilization  
      What do we expect?
      Reference work or portfolio. Examples what have you already done and what projects you have worked on academic or otherwise. The ability to commit to the project on a regular basis. If you are going on a two-week trip, we don't mind, but it would be good if you could commit 10+ hours to the project each week. Willingness to work with a royalty based compensation model, you will be paid when the game launches. Openness to learning new tools and techniques
       
      What can we offer?
      Continuous support and availability from our side. You have the ability to give design input, and creative say in the development of the game. Shown in credits on websites, in-game and more. Insight and contacts from within the Industry.
       
      Contact
      If you are interested in knowing more or joining, please email or PM us on Skype. A member of our management team will reply to you within 48 hours.
       
      E-mail: Recruitment@ForgedInteractive.com
      Skype: ForgedInteractive
       
      Regards,
      David, Colin and Joseph
       
      Follow us on:
      Facebook: https://www.facebook.com/ForgedInteractive/
      Twitter: @ForgedInteract
      Youtube: https://www.youtube.com/channel/UCpK3zhq5ToOeDpdI0Eik-Ug?view_as=subscriber
      Reddit: www.reddit.com/user/Forged_Interactive

    • By dell96
      I'm trying to make my first project but I'm stuck i don't know how to make my crate to start to spawn again when i hit the start button after i die.
      hoping someone can help!!!
      Crate.cs
      CrateSpawn.cs
      Cratework.cs
      GameController.cs
      GameManager.cs
  • Popular Now