Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string reference of a concatenation is safe?

Tags:

c++

I was reading some code that has been in use for a long time without problems, below I have a simplified version:

void SomeClass::someMethod(const std::string& arg1, const std::string& arg2) {
    // unrelated code
    const std::string& var = arg1 + arg2;
    // var used in other concatenations
    // var used to index a map
}

I would have assumed that var is not safe to use because it references a temporary. The lifetime of the temporary here is too short or does it live until the end of the method?

like image 397
asimes Avatar asked Jan 25 '18 19:01

asimes


2 Answers

const std::string& var = arg1 + arg2;

Here a lifetime of a temporary is prolonged up to the lifetime of var. It means, that the code is, generally speaking, safe.

From lifetime of a temporary:

Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference, ...

like image 156
Edgar Rokjān Avatar answered Oct 17 '22 23:10

Edgar Rokjān


The lifetime of the temporary here is too short or does it live until the end of the method?

The temporary will be alive as long as the reference is alive. In other words, it is safe to use the reference.

like image 5
R Sahu Avatar answered Oct 18 '22 00:10

R Sahu