【发布时间】:2012-06-26 08:37:04
【问题描述】:
void fn(string &s)
{
//....
}
//use the function
fn("helloworld");
首先,用 const char 字符串初始化非 const 字符串是错误的。
我在参数中添加 const 后,它会编译。
但是在堆栈上引用一个临时对象字符串(“helloworld”)是否正确?
确定调用了 string("helloworld") 吗?
--
编辑。
如果创建了临时字符串,编译器如何从std::string(const char*)的构造函数判断对象string("helloworld")是const?
【问题讨论】:
-
如果您询问是否会从
const char*创建string对象,那么答案是肯定的,您可以在函数中安全地使用该字符串。 -
创建了一个临时对象:conversion by constructor。
std::string析构函数在对象范围的末尾被调用 - 当fn()返回时。
标签: c++