[英]Is passing const reference to a temporary string object safe in C++?
考虑函数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.
假设您没有在某个位置存储对参数的引用或指针,并希望它在从函数返回后仍然存在,那么应该没问题:调用函数时,将创建一个临时的std::string
,执行该功能的时间。
函数返回后不使用它是安全的。
因此,即使该字符串对象存在更长的时间(并且使用时间更长),使用它初始化另一个字符串对象(在函数返回之前)也是安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.