Thans for your explanation.
It cleared soemthing out fo my mind, but not all of them.
It gives the impression that it is a gcc specific feature and the standard
does not require this. I'd rather it gives a warning. Because even I pass a
temporary string& s and modifiy it, it won't make any damages to my program.
I think the 'temporary' variable is just like a casual declared variable
(like string tempABC) with same life scope (Am I right?), but needs less
keystrokes. Less strokes and no errors - that's what programmers always
want!
----Original Message Follows----
From: Eljay Love-Jensen <eljay@xxxxxxxxx>
To: Neo Anderson <neo_in_matrix@xxxxxxx>, gcc-help@xxxxxxxxxxx
Subject: Re: Puzzled by const string& parameter
Date: Fri, 24 Jun 2005 07:09:33 -0500
Hi Neo,
When you declare a function like this...
void test(string& s);
You are telling the compiler "the test function is going to modify the
parameter s". That is to say, s is an output (or update) parameter.
When you call the function like this...
test(string("abc"));
...you are creating a temporary, anonymous string object, and passing it in
to test. The compiler *KNOWS* (because you told it) that the string
parameter is an output parameter. The compiler also knows that a temporary,
anonymous used as an output parameter is 99% likely to be a mistake -- why
would you intentionally want to throw away the results of the routine? So
likely is it to be a mistake, that it is actually disallowed by the ISO
14882 C++ standard -- it's a C++ programming error. (Also, because of
helpful conversions, you may get temporaries when you didn't expect them.
That is the compelling reason that this situation is a disallowed. Your
example is "obvious it is a temporary; it's explicit" ... but that's because
it is a simple and straightforward example.)
There are a few tricks that I could show you on how to (legitimately) get
around the compiler's complaint. But, in my experience, those tricks are
circumspect dirty tricks and should never be employed in real code. Send me
a private email if you are curious on how to get a legit non-const reference
to a temporary variable -- but in my opinion it's not worth the bother.
When you declare the function...
void test(string const& s);
...you are telling the compiler that the parameter is an input only
parameter, and hence temporaries are okay.
If you really don't like the parameter to be const, you could also do
this...
void test(string s);
...and then the compiler *KNOWS* that the pass-by-value parameter is not an
output parameter (so temporaries are okay) *AND* you can modify it within
the routine.
HTH,
--Eljay