KDAB / KDAlgorithms

Algorithm wrappers
Other
82 stars 15 forks source link

find_if creates dangling references for r-value references. #50

Closed LeonMatthesKDAB closed 1 year ago

LeonMatthesKDAB commented 1 year ago

kdalgorithms::find_if if called with a temporary r-value reference, results in name returning a reference to the collection, which has already been deleted.

find_if only has an overload for l-value references, which returns an iterator result. With l-values, this works fine, but if used with an r-value reference, as in the example below, the collection will be deleted as soon as the find_if has finished executing. This means any dereference of the returned name may segfault (in my case it didn't until a few days after implementing this :see_no_evil: ).

Ideally find_if should have an overload for r-value references, that returns the result by-value, instead of by-reference. That way the code below would work without issue and avoid any copies, as the result could simply be moved out of the container and still wouldn't need to be copied.

Example:

auto name = kdalgorithms::find_if(match.getAll("message-name"), [&range](const auto &name) {
        return range.contains(name);
    });