Re: Puzzled by const string& parameter

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux