考虑函数 f
void f(const std::string& s) {
...
}
像下面这样用固定字符串调用 f 是否安全:
f("abc");
最佳答案
从 "abc"
隐式构造的 std::string
的生命周期是直到对 f()
的调用结束。只要您不在 f()
结束后将引用保存在其他地方,它就绝对安全。
std::string const *pstr;
void f(std::string const &s)
{
s.length(); // safe. s has an instance backing
// it for the lifetime of this function.
pstr = &s; // still technically safe, but only if you don't
// dereference pstr after this function completes.
}
f("abc");
pstr->length(); // undefined behavior, the instance
// pstr pointed to no longer exists.
关于c++ - 将 const 引用传递给 C++ 中的临时字符串对象是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13829714/