0

Does anyone know, why the following code does not raise a warning?

struct Foo
{
    int a = 1;
};

struct Bar
{
    Foo getString()
    {
        return Foo();
    }
};

int main()
{
    Bar a;
    const Foo& b = a.getString();   <--- Foo getString() becomes Foo&?
}

https://gcc.godbolt.org/z/GYzWa7

Daniel Stephens
  • 2,371
  • 8
  • 34
  • 86
  • 6
    There's nothing to warn about. By binding a const reference to the temporary returned by getString it's lifetime is extended to match the lifetime of the reference. – john Aug 04 '20 at 17:59
  • 1
    @John I think you should turn that comment into a proper answer. – Jesper Juhl Aug 04 '20 at 18:01
  • 1
    https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ – Mat Aug 04 '20 at 18:02
  • 1
    @JesperJuhl I wasn't completely sure I was answering the question that the OP was asking. They might have some other reason for thinking a warning was needed. – john Aug 04 '20 at 18:04
  • That's fine! Thanks a lot! That would exactly answer my question – Daniel Stephens Aug 04 '20 at 18:04
  • https://stackoverflow.com/questions/39718268/why-do-const-references-extend-the-lifetime-of-rvalues – Mat Aug 04 '20 at 18:04
  • 2
    OK now it's an official answer. – john Aug 04 '20 at 18:05

1 Answers1

5

There's nothing to warn about. By binding a const reference to the temporary returned by getString its lifetime is extended to match the lifetime of the reference.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
john
  • 85,011
  • 4
  • 57
  • 81
  • Related question : [Does a const reference class member prolong the life of a temporary?](https://stackoverflow.com/questions/2784262/does-a-const-reference-class-member-prolong-the-life-of-a-temporary). – François Andrieux Aug 04 '20 at 18:33