[Xfc-dev] pointers vs. references in XFC
Jeff Franks
jcfranks at tpg.com.au
Fri Mar 4 19:34:45 CET 2005
Brian J. Tarricone wrote:
> Hi Jeff,
>
> Going through the tutorials and examples on the site (damn! so much
> information - well done!), I noticed that most functions take object
> references as parameters, rather than pointers. However, widgets are
> still created with operator new, so it seems that, aside from use of
> smart pointers, we're usually going to have pointers to widgets, but
> we have to do things like this:
>
> a_gtk_box->pack_start(*button, ...);
>
> It seems kinda annoying to me to always have to dereference the widget
> pointer when passing it to functions. I'm just curious to know why
> this approach was taken.
>
There are pros and cons for using pointers and references. C++
programmers tend to prefer references but C/C++ programmers tend to
prefer pointers because C doesn't have references. Some C++ experts
argue the case for using both, depending on the circumstance, and some
argue to case for references only. References are safer to use that
pointers. After reading several articles on the issue I decided to use
both, and that's the way it has been ever since. I did look at using
only references and smart pointers (like Gtkmm) but the syntactical
changes would have been huge and the API more complicated. The
alternative would be to drop references altogether and use only
pointers. This is what Havoc did in the original Inti library. Both are
a part of the C++ language and have their valid uses.
Currently, whether a function parameter is passed as a reference, or a
pointer, hinges on whether the parameter can be null. If the parameter
must never be null it's passed as a reference and if it can be null it's
passed as a pointer. The choice depends on how GTK+ declares the
corresponding C function body. Most GTK function bodies begin with one
or more "g_return_val_if_fail" lines which check for null arguments and
return an error. These C++ parameters are all passed as references.
Other parameters are not checked for null but GTK does something like "
if (argument != 0) do something like set value ". These C++ parameters
are all passed as pointers. The benefit of using references is that XFC
function bodies don't need to check those parameters for null or pass
exceptions if an error occurs. Also users know that a reference means a
parameter cannot be null and a pointer means it can.
That was the short answer,
Regards,
Jeff.
More information about the Xfc-dev
mailing list