3

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?

Fedor
  • 17,146
  • 13
  • 40
  • 131
  • 2
    Please remember to make questions *self-contained*. If you ask about compiler messages, then please include them copy-pasted as text inside the question itself. – Some programmer dude Jul 12 '21 at 06:56
  • 1
    Clang is returning an error and not a warning for z: "error: reference member 'a' binds to a temporary object whose lifetime would be shorter than the lifetime of the constructed object struct B" – Alessandro Teruzzi Jul 12 '21 at 08:07
  • 1
    The example can be simplified removing the struct A and using int instead, same pattern of warnings. Also, this [[maybe_unused]] B b = B{}; produce no warnings as [[maybe_unused]] auto x = B{}; – Alessandro Teruzzi Jul 12 '21 at 09:51
  • @AlessandroTeruzzi, thanks, I updated the question based on your findings – Fedor Jul 12 '21 at 10:25

0 Answers0