0

Please consider the following C++20 program:

struct S {
  S(int x) : x(x) {}

  int x;
};

S f() { return S(42); }

int main() {
    auto&& r = f().x;
    return r;
}

Is this undefined behaviour and the reference dangles? or is the int object lifetime extended?

Andrew Tomazos
  • 66,139
  • 40
  • 186
  • 319
  • _"...Whenever a reference is bound to a temporary or to a __subobject__ thereof, the lifetime of the temporary is extended to match the lifetime of the reference..."_ https://en.cppreference.com/w/cpp/language/reference_initialization#Lifetime_of_a_temporary My reading is the life-time of the temporary `S` ( returned from `F()` ) is extended. – Richard Critten Feb 24 '21 at 13:27
  • @RichardCritten: It looks like it works in recent versions of gcc and clang, but not in msvc. See comment in linked question. – Andrew Tomazos Feb 24 '21 at 13:50

0 Answers0