Abruzzo Forte e Gentile
Abruzzo Forte e Gentile

Reputation: 14879

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?

Upvotes: 14

Views: 7718

Answers (1)

juanchopanza
juanchopanza

Reputation: 227578

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

Upvotes: 21

Related Questions