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);
                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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With