Re: Puzzled by const string& parameter

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

 



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@xxxxxxxxx>
To: Neo Anderson <neo_in_matrix@xxxxxxx>, gcc-help@xxxxxxxxxxx
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



[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