Skip to content

Invalid value access with sequence ".filter_map().to()" when resulting sequence is empty #237

@BlackCrowned

Description

@BlackCrowned

There seems to be an issue when iterating over a sequence with filter_map and storing the result in a container.

Please see the following example:

https://godbolt.org/z/TfdKdzfr9

#include <iostream>
#include <random>

int main()
{
    auto test = 0;
    try {
        auto const test_input = std::vector<int>(10, 1); // Vector full of 1s
        auto const result = flux::from_range(test_input)
            .map([](auto const& i) -> std::optional<int>
            {
                if ((i % (rand() % 100 + 1)) == 0) {return 5;} // Never executed
                return {};
            }) // -> Sequence full of empty optionals
            .filter([](auto const& opt) {return opt.has_value();}) // Should filter out empty optionals  -> Empty sequence
            .map([](auto const& opt) {return opt.value();}) // Should never encounter an empty optional
            .to<std::vector>();
        
        test += result.size();
    }
    catch(std::exception const& ex)
    {
        std::cout << ex.what() << std::endl;
        return 54;
    }

    return test;
}

Expected Outcome

Program returns with value 0.

Actual Outcome

Program returns with value 54, and bad optional access exception

Notes

This might be just an issue with MSVC compiler as it seems to run fine on gcc.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions