0
int x = 100;
int& f() { return x; }
auto g = []() mutable -> int& { return x; };
std::function<int&()> funcfunc()
{
    std::cin >> x;
    int& (&h)() = x > 0 ? f : g;
    return h;
}

Somehow it compiles with MSVC, while clang and gcc believe g could not convert to int&(*)() and then be used to initialize h with type 'int&(&)()'

  • 2
    What version of MSVS are you using? `g` should decay into a prvalue function pointer, so you should not be able to bind a non-const lvalue reference to it. related/maybe dupe: https://stackoverflow.com/questions/16380966/non-const-reference-bound-to-temporary-visual-studio-bug – NathanOliver Dec 16 '21 at 14:06
  • This should probably be written `if (x > 0) return f; else return g;`. (there seems to be a rash of ternary operator abuse lately...) – Pete Becker Dec 16 '21 at 14:09
  • On godbolt it compiles only if C++20 is activated: https://godbolt.org/z/hc6oE5vWj with C++17 MSVC reports an error too. – Marek R Dec 16 '21 at 14:13
  • And here is fixed version: https://godbolt.org/z/Mab9jr1Wc (compiles everywhere). Reference to a function doesn't make seance anyway. – Marek R Dec 16 '21 at 14:15

0 Answers0