6

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?

asimes
  • 5,749
  • 5
  • 39
  • 76
  • 5
    It is fine, const reference extends lifetime of a temporary – Slava Jan 25 '18 at 19:02
  • 1
    Possible dupe https://stackoverflow.com/questions/36982630/does-const-reference-prolong-the-life-of-a-temporary-object-returned-by-a-tempor – Rakete1111 Jan 25 '18 at 19:02
  • @Rakete1111 I do not think so, that question about a temporary returned by temporary. But i bet there is a dup already – Slava Jan 25 '18 at 19:03
  • @Slava In both cases a temporary is assigned to a `const&` though. It doesn't really matter how that temporary came to be. – Rakete1111 Jan 25 '18 at 19:04
  • 1
    @Rakete1111 yes behavior is the same, but question is different - author of that one worried that intermediate temporary would affect correctness of the statement so I do not think this is the dupe. – Slava Jan 25 '18 at 19:06

2 Answers2

14
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, ...

Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
  • Rokyan, is that valid even if `var` is not `const` ? – Mohammad Kanan Jan 25 '18 at 19:07
  • 5
    @MohammadKanan you cannot assign prvalue to lvalue reference, unless you have Microsoft compiler. – Slava Jan 25 '18 at 19:07
  • @MohammadKanan try to bind non const reference to a temporary and see what the compiler says :) – Edgar Rokjān Jan 25 '18 at 19:07
  • 4
    @EdgarRokyan As Slava points out, if you try it in Visual Studio it'll appear to be fine. While "Try it and see" may be a good way of learning certain programming languages, c++ is not one of those languages. The existence of UB makes it very difficult to learn c++ by trial. – François Andrieux Jan 25 '18 at 19:09
  • @FrançoisAndrieux ah, they have this extension which allows to bind non const references to temporaries... you're right! – Edgar Rokjān Jan 25 '18 at 19:10
5

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270