有人知道为什么下面的代码没有引发警告吗?
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
没有什么可警告的。通过将const
引用绑定到由getString
返回的临时,其生存期被延长以匹配引用的生存期。