Why seemingly equivalent object constructions produce different warnings in C++?

Viewed 88

I am rather surprised that 3 object constructions, which I considered equivalent, actually produce different compiler warnings or even an error:

struct B { int &&a = {}; };

int main()
{
    [[maybe_unused]] auto x = B{}; //ok in clang and gcc
    [[maybe_unused]] B y{}; //clang warning
    [[maybe_unused]] B z; //gcc warning and clang error
}

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

GCC warning about z:

warning: a temporary bound to 'B::a' only persists until the constructor exits [-Wextra]

Clang warning about y:

warning: sorry, lifetime extension of temporary created by aggregate initialization using default member initializer is not supported; lifetime of temporary will end at the end of the full-expression [-Wdangling]

Clang error about z:

 error: reference member 'a' binds to a temporary object whose lifetime would be shorter than the lifetime of the constructed object

Could you please explain what is the difference between these 3 construction methods?

0 Answers
Related