Puzzled by const string& parameter

Neo Anderson neo_in_matrix@msn.com
Fri Jun 24 20:25:00 GMT 2005


Thanks for replying.

Let's end this talk because no matter what *I* think, the standard IS the 
standars. I can't change it.

----Original Message Follows----
From: Eljay Love-Jensen <eljay@adobe.com>
To: Neo Anderson <neo_in_matrix@msn.com>, gcc-help@gcc.gnu.org
Subject: Re: Puzzled by const string& parameter
Date: Fri, 24 Jun 2005 11:24:58 -0500

Hi Neo,

 >If this code compiles under gcc, where is the DOH?

#include <string>
using std::string;

void test(string& s)
{
     s = "abc";
}

int main()
{
     test(string("123"));
}

That code does not compile under GCC 3.3.3.

neo.cpp: In function `int main()':
neo.cpp:11: error: invalid initialization of non-const reference of type 
'std::string&' from a temporary of type 'std::string'
neo.cpp:5: error: in passing argument 1 of `void test(std::string&)'

The "DOH" is in the anonymous temporary being passed into the test function, 
when you've specified that the parameter in the test function cannot be a 
temporary.

The compiler indicates this error:  "invalid initialization of non-const 
reference of type 'std::string&' from a temporary of type 'std::string'".

To thwart the compiler, you could do this:

test((string&)(string const&)string("123"));

Or you could make a string wrapper which has an operator to return a 
non-const reference to the actual string.

HTH,
--Eljay




More information about the Gcc-help mailing list