[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: passing temporary storage as a non-const parameter to a function
From: |
Lionel B |
Subject: |
Re: passing temporary storage as a non-const parameter to a function |
Date: |
9 Nov 2004 01:43:07 -0800 |
User-agent: |
G2/0.2 |
jjleto wrote:
> 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)
Correct behaviour.
> 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 ?
Use a temporary.
int main()
{
f1(string("foo")); // OK
string msg("foo");
f2(msg); // OK now (msg not temporary).
}
Alternatively:
void f2(const string& msg) {string tmp(msg); tmp+="bar"; cout << tmp
<< endl;}
Regards,
--
Lionel B