简体   繁体   English

std::string::substr 返回的 object 的生命周期

[英]Lifetime of the object returned by std::string::substr

I need to know whether the following is valid in general.我需要知道以下内容是否普遍有效。

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

Is the assignment to v always valid?v的分配总是有效的吗? Can there be any issues due to the temporary lifetime of object returned by substr() .由于substr()返回的 object 的临时生命周期,是否存在任何问题。

It's valid here.在这里有效。 The temporary returned by substr is destroyed after the full expression; substr返回的临时值在完整表达式之后被销毁; which includes the initialization of v .其中包括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.即使评估以抛出异常结束也是如此。

BTW: This is not assignment but initialization (construction) of v .顺便说一句:这不是赋值,而是v的初始化(构造)。

The assignment to v is valid.v的赋值是有效的。 Temporary objects are not destroyed until the end of the whole statement is finished (when the ; is reached), which is after the assignment is complete.直到整个语句结束(当到达;时),也就是赋值完成之后,临时对象才会被销毁。

However, in this particular example, the use of c_str() is redundant and inefficient.然而,在这个特定的例子中,使用c_str()是多余的和低效的。 It requires iterating the char data to determine its length, which the temp string returned by substr() already knows, so just assign the returned string as-is:它需要迭代char数据以确定它的长度, substr()返回的临时string已经知道,所以只需按原样分配返回的string

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

substr returns a newly constructed string object with its value initialized to a copy of a substring of this object. substr返回一个新构造的字符串对象,其值初始化为此 object 的 substring 的副本。

So you are safe所以你是安全的

Once you've assigned a variable, it is under the protection of the scope of the variable.一旦你分配了一个变量,它就会受到变量 scope 的保护。 It will not change till you change it, or it loses scope, as I said.正如我所说,除非你改变它,否则它不会改变,否则它会丢失 scope。 There is only a "temporary lifetime" if you have the instantiation nested.如果嵌套了实例化,则只有“临时生命周期”。

My own quote above.上面我自己的报价。 All you're asking about is "How or when does the.substr function look in the memory for it, and does it stay in memory?"您要问的只是“.substr function 如何或何时在 memory 中查找它,它是否留在 memory 中?” The answer is its copy is in the assignment to the left value.答案是它的副本在左值的赋值中。 Considering that, the.substr function's action on the memory is lost.考虑到这一点, .substr 函数对 memory 的操作丢失了。 So yes it is temporary.所以是的,它是暂时的。 But as I vaguely asserted already, that is temporal to the scope of the variable.但正如我已经模糊断言的那样,这对于变量的 scope 是暂时的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM