Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a const char instead of a std::string as function argument

This is a newbie question but I cannot understand how it works.

Suppose I have the function like the one below

void foo(const std::string& v) {
    cout << v << endl;
}

And the call below in my program.

foo("hi!");

Essentially I am passing a const char* to a function argument that is const reference to a string so I have a doubt on this call.

In order to pass an argument by reference, am I right to say that the variable must exist at least for the duration of the call? If it is so, where is created the string that is passed to the function?

I can see that it works : does it happen because the compiler creates a temporary string that is passed to the argument or the function?

like image 788
Abruzzo Forte e Gentile Avatar asked Jan 28 '14 14:01

Abruzzo Forte e Gentile


1 Answers

does it happen because the compiler creates a temporary string that is passed to the argument or the function?

Yes, and temporaries are allowed to bind to const lvalue references. The temporary string v is alive for the duration of the function call.

Note that this is possible because std::string has a implicit converting constructor with a const char* parameter. It is the same constructor that makes this possible:

std::string s = "foo";
like image 84
juanchopanza Avatar answered Oct 07 '22 09:10

juanchopanza