[Kde-bindings] To copy or not to copy
Arno Rehn
arno at arnorehn.de
Sat Aug 8 11:44:00 UTC 2009
On Saturday 08 August 2009 04:00:01 Chris Burel wrote:
> I'm curious about this code from QtRuby, in it's SmokeClassWrapper
> toRuby handler:
> if(m->type().isConst() && m->type().isRef()) {
> p = construct_copy( o );
> ...
> if(p) {
> o->ptr = p;
> o->allocated = true;
> }
> }
>
> I suppose it's difficult to know when the user would want a copy set
> up for them. But for some things it seems like it's nicer to not
> return a copy of the object being returned. For instance, QWidget's
> font() or palette() methods return a const ref, so the user gets a
> copy back. This means that to change a widget's font or palette, they
> have to get the font, change it, and set it back. If a copy wasn't
> constructed, whatever changes they make to the font or palette would
> take effect without having to call setFont or setPalette, which seems
> more desirable (and more like the C++ Qt interface).
The thing is, that it is a _const_ reference. So you can't change it in C++,
too (if you don't do a const_cast - but then bad things may happen). Since
most other languages don't have constant local variables, we have to return a
copy here so the user can't change the underlying C++ object.
> The downside I see, if we don't return a copy, that sometimes it would
> be confusing because data could change out from underneath the user.
> For example, QMouseEvent has a pos() function, which returns a const
> QPoint &. From my experience, it actually returns the *same* QPoint
> ref for each event, just with different data. So if the user is
> trying to store positions of mouse clicks and doesn't manually create
> a copy, they won't actually save anything.
const return types are mostly a way of avoiding copying memory if it's not
necessary (from my experience). If you just want to inspect some properties of
the font of a widget, you simply do
const QFont& font = widget->font();
int i = font.blah();
This avoids copying memory but you still have the font accessible as a local
variable. If you really want to store a value, you have to create a copy of
that, of course. Most bindings languages don't have const types, so we always
need to create copies.
--
Arno Rehn
arno at arnorehn.de
More information about the Kde-bindings
mailing list