1

考虑函数 f

void f(const std::string& s) {
    ...
}

使用固定字符串调用 f 是否安全,如下所示:

f("abc");
4

3 回答 3

8

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.
于 2012-12-11T22:44:32.073 回答
2

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.

于 2012-12-11T22:44:45.257 回答
0

函数返回后不使用是安全的。

因此,使用它来初始化另一个字符串对象(在函数返回之前)也是安全的,即使这个字符串对象的寿命更长(并且使用时间更长)。

于 2012-12-11T22:43:09.173 回答