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

c++, parameter-passing, pass-by-reference

Solution

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";

Problem

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?

Original source