Re: Puzzled by const string& parameter

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

 



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