[mythtv] API suggestions

Joseph A. Caputo jcaputo1 at comcast.net
Fri Feb 6 16:28:04 EST 2004


On Friday 06 February 2004 14:49, Renchi Raju wrote:
> On Fri, 6 Feb 2004, Henrik (Mauritz) Johnson wrote:
> > Renchi Raju wrote:
> > >"const QString& function()" never hurts. in fact i would recommend
> > > it over just plain  "QString function()"
> >
> > I beg to differ. Take the current example:
> >
> > const QString &returnString(void)
> > {
> >    return "Here we go much to fast. Watch out boy were gonna
> > craash."; }
> >
> > This will result in corrupted stack and a crash three function
> > calls later and a couple of hours debugging. Still, sometimes it's
> > ok as long as the returned string isn't garbage collected on return
> > from the function but then were back to "you are very sure of what
> > you are doing".
>
> this is just plain stupid and should have been obvious. you created
> something on the stack and returned it by reference. if it wasn't
> obvious i was referring to returning a const reference to a member
> data.

Right.  I still maintain that one should avoid returning "const QString 
&" from a function in most cases, *unless* you specifically do *not* 
want the copy-on-write behavior.  Holding a reference to a QString like 
that means that you (and anyone else holding a reference to the same 
object) will silently get any modifications made to that object by 
anyone, anwhere in the program.  Admittedly, sometimes this is what you 
want, but I'd say usually it is not the desired behavior.  Reference 
variables are a C++-ism that was created to try and eliminate some of 
the confusion and problems presented by pointers, while still retaining 
the advantage of reduced call stack overhead.  I'm not entirely 
convinced they were a good idea -- they can create as many problems as 
they solve if used carelessly.  Anyway, Qt solves the problem with 
implicitly shared classes, which mitigate the overhead of passing 
objects by value on the call stack, so you don't need to resort to 
passing references unless you have good reason.

-JAC



More information about the mythtv-dev mailing list