函数参数字符串按引用传递

function parameter string pass by reference

void print(const string& str){
    cout << str <<endl;;
}

int main(){
    print(string("asdf"));
}

我想我可以这样理解 创建了一个临时字符串对象,并通过引用将其传递给函数。参数 str 实际上是与那个临时字符串对象完全相同的对象。

但是如果我用 print("asdf"); 替换调用呢? 在这种情况下到底发生了什么? 我知道涉及隐式转换。但我不确定它是何时以及如何完成的? 我的意思是是否也创建了一个临时字符串对象?

是的,因为 string 有接受 const char* (string (const char* s)) 的构造函数,并且这个构造函数没有标记 explicit,编译器将构建等同于你的问题。

你的理解是正确的。

What is exactly happening in this case? I know implicit conversion is involved.

发生完全相同的事情,但涉及隐式转换,而不是显式调用构造函数。


But I am not sure when and how it is done?

引自cppreference

Implicit conversions are performed whenever an expression of some type T1 is used in context that does not accept that type, but accepts some other type T2


I mean is it there is a temporary string object created as well?

是的。