[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
passing temporary storage as a non-const parameter to a function
From: |
jjleto |
Subject: |
passing temporary storage as a non-const parameter to a function |
Date: |
Tue, 09 Nov 2004 07:51:44 +0100 |
User-agent: |
Mozilla/5.0 (X11; U; Linux x86_64; fr-FR; rv:1.7.3) Gecko/20040924 Debian/1.7.3-1ubuntu1 |
Hello,
When I compile the following code:
#include <iostream>
#include <string>
using namespace std;
void f1(const string& msg) { cout << msg << endl; }
void f2(string& msg) { cout << msg << endl; }
int main()
{
f1(string("foo")); // OK
f2(string("foo")); // NOK.
}
I've got the following error on the line calling f2():
error: invalid initialization of non-const reference of type
'std::string&' from a temporary of type 'std::string' (gcc 3.3.4)
I understand that in this case, if I changed the string in the function,
i could not use it after the function returns; but in some cases, I need
to use it.
How do I handle this ?
Thanks.
- passing temporary storage as a non-const parameter to a function,
jjleto <=