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?
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, ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With