考虑函数 f
void f(const std::string& s) {
...
}
使用固定字符串调用 f 是否安全,如下所示:
f("abc");
std::string
隐式构造 from的生命周期"abc"
是直到调用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.
Assuming you don't store a reference or a pointer to the argument somewhere and hope that it is still around once you returned from the function, it should be OK: when the function is called, a temporary std::string
is created which is around for the time the function is executed.
函数返回后不使用是安全的。
因此,使用它来初始化另一个字符串对象(在函数返回之前)也是安全的,即使这个字符串对象的寿命更长(并且使用时间更长)。