gpt4 book ai didi

c++ - 函数参数字符串按引用传递

转载 作者:行者123 更新时间:2023-11-30 02:31:06 33 4
gpt4 key购买 nike

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

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

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

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

最佳答案

你的理解是正确的。

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?

是的。

关于c++ - 函数参数字符串按引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38010645/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com