[英]Can we pass a char* to const string&?
Is the following code acceptable in C++? 以下代码在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. 编译器将调用
string(const char *)
构造函数,并创建一个临时对象,该临时对象将在调用期间绑定到s
。 When the fall to f
returns the temporary will be destroyed. 当跌落至
f
时,该临时物品将被销毁。
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. 作为字符数组的参数被隐式转换为std :: string类型的临时对象,并且编译器将对该临时对象的const引用传递给函数。 When the statement with the call of the function will finish its work the temporary object will be deleted.
当带有函数调用的语句完成工作时,临时对象将被删除。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.