3

Consider the following code, which contains a templated std::vector type of std::function objects which consume a const & std::range and std::range::iterator. What causes the position std::ranges::iterator_t passed into the std::functional lambda to be invalidated, such that on g++ and clang++, the std::cout iteration goes passed the end of the std::string?

#include <ranges>
#include <string>
#include <iostream>
#include <vector>
#include <functional>

int main(const int, const char * []) {
    auto consume = [](const auto & source, auto position) {
        auto consumption = std::ranges::subrange(position, std::end(source));
        for (auto res : consumption) {
            std::cout << res;
        }
    };

    std::vector<std::function<void(
            std::string,
            std::string::const_iterator)>> lambdas{consume};
    const auto range = std::string("hello");
    lambdas.back()(range, std::begin(range));
}

I am uncertain what else is unnecessary for the minimal viable example (Better ASAN'd version courtesy of @Marek R), but I've done my best to trim.

Robbie
  • 287
  • 1
  • 9

0 Answers0