Reputation: 1027
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);
Upvotes: 4
Views: 2109
Reputation: 8961
Does it create a temp string variable and pass its address?
Yes, it's equivalent to:
void f(const std::string& s) {
}
const char kJunk[] = "junk";
f(std::string(kJunk));
Upvotes: 2
Reputation: 311088
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.
Upvotes: 3
Reputation: 62532
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.
Upvotes: 14