Daniel Stephens
Daniel Stephens

Reputation: 3209

Why does converting an rvalue into an lvalue ref not raise a warning?

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

Upvotes: 0

Views: 43

Answers (1)

john
john

Reputation: 87959

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.

Upvotes: 5

Related Questions