Rationale of non-const reference to temporaries
Hello,
I would like to submit the following code to your attention:
#include <string>
#include <iostream>
void f(std::string& s)
{ std::cout << s << std::endl; }
int main(int argc, char* argv[])
{
std::string s("Hello world");
f(s); // <- This is ok
f(std::string("Hello world")); // <- This is incorrect (g++)
return 0;
}
It compiles without errors on VC++ 8.0 (2005), while on gcc 4.1.2
(and later) it gives the following error:
g++ -O2 -g -Wall -fmessage-length=0 -c -o main.o main.cpp
main.cpp: In function 'int main(int, char**)':
main.cpp:11: error: invalid initialization of non-const reference of
type 'std::string&' from a temporary of type 'std::string'
main.cpp:4: error: in passing argument 1 of 'void f(std::string&)'
make: *** [main.o] Error 1
What I know is that temporaries can be passed as const references
and that VC allows passing them as non-const references as an
extension to the standard.
What I don't know precisely is whether there is any potential risk
of error in doing as above.
Could you help me understand the rationale of the two approaches?
Thanks in advance,
eca
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]