Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should deduction guide for std::optional be applied when passing std::ref(value)?

Background

I'd like to run some functions in sequence, short-circuiting when one of them succeeds. They all have the same return type, are mostly zero argument callables (lambdas with captures). To identify success, the function returns non-empty optional. The thing is that sometimes those functions return references, in which case writing

return std::optional{some_reference};

will be UB. But, it seems like doing

return std::optional{std::ref(some_reference)} ;

is not. GCC 9 happily compiles that. Though clang 7 doesn't.


Full code:

#include <optional>
#include <functional>
#include <iostream>

int main()
{
    int x = 12;
    auto job = [](const int& y)
    {
        return std::optional{std::ref(y)};
    };
    auto value = job(x);
    x = 25;
    std::cout << *value << '\n';
}

Question

Which one of them is right?


I believe the code should compile, because class template argument deduction should be applied and std::reference_wrapper<int> deduced.

like image 616
Incomputable Avatar asked Mar 03 '26 00:03

Incomputable


1 Answers

The code in OP is well-formed and should yield an optional<reference_wrapper<int>>.

This is llvm bug 34650. A simpler example demonstrating the problem is:

std::optional o(42);

gcc allows it (with o being a std::optional<int>), clang does not.

like image 110
Barry Avatar answered Mar 04 '26 14:03

Barry