简体   繁体   中英

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? Can there be any issues due to the temporary lifetime of object returned by substr() .

It's valid here. The temporary returned by substr is destroyed after the full expression; which includes the initialization of 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 .

The assignment to v is valid. 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. 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:

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.

So you are safe

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.

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?" 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. So yes it is temporary. But as I vaguely asserted already, that is temporal to the scope of the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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