[Qt-interest] Strange (as for me) QByteArray behavior
Konrad Rosenbaum
konrad at silmor.de
Wed Dec 8 19:03:38 CET 2010
On Wednesday 08 December 2010, Paul Miller wrote:
> On 12/8/2010 2:31 AM, Thiago Macieira wrote:
> > On Wednesday, 8 de December de 2010 09:07:52 Konrad Rosenbaum wrote:
> >> On Wednesday 08 December 2010, Ivan Kharin wrote:
> >>>> QByteArray tmp = username.toAscii();
> >>>
> >>> const QByteArray&tmp = username.toAscii(); // avoid copy: const ref
> >>> to function result == // keep automatic variable intact until end
> >>> of scope
> >>
> >> I don't think this can work reliably. C++ is not a garbage collected
> >> language, the reference becomes invalid immediately after the
> >> semicolon.
> >
> > That's not correct. The above is perfectly valid C++.
I stand corrected.
> How does that work? Is the temporary QByteArray returned from toAscii()
> somehow kept around on the stack once the reference to it is made?
I just did some experiments - giving the non-reference return value of a
function (or method) a name by referencing it seems to expand its scope
beyond the expression it is used in.
You can imagine what the compiler does like this:
When it reaches the semicolon of the expression it tries to decide what to
do about all the temporary objects it just created (return values of
functions, methods and operators):
a) if the temporary value does not have a name - kill it
b) if it has a name (i.e. a reference that is visible beyond the semicolon,
or it is a variable declared on this line) then expand its scope as far as
that reference is visible
After that the normal scope checking kicks in: as soon as the value hits its
new end of scope: kill the value.
Don't worry, you can still shoot yourself in the foot with references. They
are not magical - merely convenient. ;-)
This whole scope-expansion only works if the reference gives a name to a
value that was temporary and anonymous until then.
Konrad
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20101208/4693282c/attachment.bin
More information about the Qt-interest-old
mailing list