Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!att!dptg!ulysses!andante!alice!ark
From: ark@alice.UUCP (Andrew Koenig)
Newsgroups: comp.lang.c++
Subject: Re: Strings
Message-ID: <10050@alice.UUCP>
Date: 24 Oct 89 18:50:31 GMT
References:
Distribution: comp
Organization: AT&T Bell Laboratories, Liberty Corner NJ
Lines: 39
In article , dl@g.g.oswego.edu (Doug Lea) writes:
> This doesn't seem like the right solution. Consider
> String& addeol(String& s) { s += "\n"; return s; }
> main()
> {
> String a, b; //...
> String c = addeol(a+b);
> //...
> }
> which would be illegal if operator+ returned a const String. (Yes,
> the form of `addeol' is contrived, but not indefensible.)
I suggest that operator+(const String&, const String&) should
return a const String precisely so that stuff like the example
above will be illegal.
The trouble with the example is that the value of a+b is a temporary
that can be destroyed as soon as addeol() returns. Thus it seems
to me that it should be OK for a compiler to generate code that
looks like this:
evaluate a+b into a temporary T
call addeol(T) and save a reference to the result
destroy T
copy the saved result of addeol() into c
In this case, the `saved result' of addeol will have been destroyed
before copying it, so c will be garbage.
You might say that this argues that the destruction of the temporary
that holds a+b should be deferred until later. Unfortunately, doing
that doesn't eliminate the problem, it just makes it less likely.
--
--Andrew Koenig
ark@europa.att.com