Re: I'm a little confused on cast_dynamic and cast_static in Glib::RefPtr.



2010/8/11 Tao Wang <dancefire gmail com>:
> Hi,
>
> It might be a basic C++ question, I'm not sure that I should asked here, but
> I'm a little confused on these 2 cast:
>
> RefPtr<Derived>::cast_dynamic(ptr_base);
> RefPtr<Derived>::cast_static(ptr_base);
>
> Say, Gtk::Action is inherited from Gtk::Object, and I get
> RefPtr<Gtk::Object>, and I need to cast to RefPtr<Gtk::Action>. Which one
> should I use?

First - Gtk::Action inherits from Glib::Object, but not from
Gtk::Object, so if you
get a RefPtr<Gtk::Object> then there is no way to cast it to
RefPtr<Gtk::Action> correctly.
But if you get RefPtr<Glib::Object> then use cast_dynamic method. Be
sure to check
if given RefPtr is not empty after casting. In this case dynamic cast
checks if given
object pointed by a pointer to base class is also a derived one. If
so, it returns a casted
pointer to given object, otherwise 0 pointer. Static cast does not
perform such checks,
so in this case such cast is unsafe.

>
> I think both static_cast<> and dynamic_cast<> can handle the cast between
> classes in the class hierarchy. But dynamic_cast do more for the RTTI type
> checking during the run time. However, if Gtk::Action is not inherited from
> Gtk::Object, (and no conversion function available between them), the code
> cannot be compiled successfully. So, it seems that it not necessary to use
> cast_dynamic() here.
>
> So, is it ok that I use cast_static() for casting from Gtk::Object to
> Gtk::Action?

No. You cannot be sure that this pointer actually points to
Gtk::Action instead of,
for example, Gtk::Builder, which also have the same base class as Gtk::Action.

> and what is the case that we should use cast_dynamic()? Thank
> you in advance.

Mostly when casting from base class to derived class. There is also such thing
like crosscasting in which dynamic cast is also used, but that is
probably rarely used.

> --
> Regards
>
> Tao Wang
>
> _______________________________________________
> gtkmm-list mailing list
> gtkmm-list gnome org
> http://mail.gnome.org/mailman/listinfo/gtkmm-list
>
>


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]