std::string::substr 返回的对象的生命周期

Lifetime of the object returned by std::string::substr

我需要知道以下是否普遍有效。

string s = "some value";
string v = s.substr(0, 50).c_str();

v 的分配是否始终有效?由于 substr().

返回的对象的临时生命周期,是否会出现任何问题?

substr returns a newly constructed string object with its value initialized to a copy of a substring of this object.

所以你很安全

Once you've assigned a variable, it is under the protection of the scope of the variable. It will not change till you change it, or it loses scope, as I said. There is only a "temporary lifetime" if you have the instantiation nested.

以上是我自己的引述。您要问的只是 "How or when does the .substr function look in the memory for it, and does it stay in memory?" 答案是它的副本在对左值的赋值中。考虑到这一点,.substr 函数对内存的操作丢失了。所以是的,这是暂时的。但正如我已经含糊地断言的那样,这对变量的范围是暂时的。

这里有效。 substr 返回的 temporary 在完整表达式后被销毁;其中包括 v.

的初始化

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception.

顺便说一句:这不是赋值而是 v.

的初始化(构造)

v 的分配有效。直到整个语句结束(到达 ; 时)临时对象才会被销毁,这是在赋值完成之后。

但是,在此特定示例中,c_str() 的使用是多余且低效的。它需要迭代 char 数据来确定其长度,substr() 返回的 temp string 已经知道,所以只需按原样分配返回的 string 即可:

string v = s.substr(0, 50);