Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we pass a char* to const string&?

Tags:

c++

Is the following code acceptable in C++? If so, what happens? Does it create a temp string variable and pass its address?

void f(const string& s) {
}
const char kJunk[] = "junk";
f(kJunk);
like image 452
Seeker Avatar asked Oct 30 '25 22:10

Seeker


2 Answers

Yes, it's acceptable. The compiler will call the string(const char *) constructor and create a temporary that will be bound to s for the duration of the call. When the fall to f returns the temporary will be destroyed.

like image 90
Sean Avatar answered Nov 01 '25 12:11

Sean


The argument that is the character array is implicitly converted to a temporary object of type std::string and the compiler passes const reference to this temporary object to the function. When the statement with the call of the function will finish its work the temporary object will be deleted.

like image 22
Vlad from Moscow Avatar answered Nov 01 '25 12:11

Vlad from Moscow