且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Lambda 适用于最新的 Visual Studio,但不适用于其他地方

更新时间:2023-09-25 12:05:34

您依赖于这样一个事实,即您传递给算法的确切闭包是用作谓词的闭包,但标准允许复制它:

You are relying on the fact that the exact closure you pass into the algorithm is the one used as the predicate, but the standard allows it to be copied:

[algorithms.general]/10 (N4140): [注意:除非另有说明,以函数对象为参数的算法是允许复制的那些功能对象***.对对象标识很重要的程序员应该考虑使用指向非复制实现对象的包装类,例如 reference_wrapper (20.9.3),或一些等效的解决方案.——结尾说明]

[algorithms.general]/10 (N4140): [Note: Unless otherwise specified, algorithms that take function objects as arguments are permitted to copy those function objects freely. Programmers for whom object identity is important should consider using a wrapper class that points to a noncopied implementation object such as reference_wrapper (20.9.3), or some equivalent solution. —end note ]

这正是 libstdc++ 所做的.从 v6.2.1 开始:

This is exactly what libstdc++ does. From v6.2.1:

template<typename _ForwardIterator, typename _Predicate>
_ForwardIterator
__remove_if(_ForwardIterator __first, _ForwardIterator __last,
            _Predicate __pred)
{
    __first = std::__find_if(__first, __last, __pred);
    if (__first == __last)
    return __first;
    _ForwardIterator __result = __first;
    ++__first;
    for (; __first != __last; ++__first)
    if (!__pred(__first))
        {
        *__result = _GLIBCXX_MOVE(*__first);
        ++__result;
        }
    return __result;
}

在函数开始时对 std::__find_if 的调用复制了 __pred,这意味着 i 的值增加了一个std::__find_if 中的位,但这不会改变呼叫站点上发生的事情.

That call to std::__find_if at the start of the function copies __pred, which means that the value of i is incremented a bit within std::__find_if, but this doesn't change what's going on at the call site.

要解决这个问题,你可以使用 std::ref:

To fix this problem, you could use std::ref:

auto clos = [i = 0U, it = cbegin(intervals), end = cend(intervals)](const auto&) mutable {
    return it != end && ++i > it->first && (i <= it->second || (++it, true));
};
values.resize(distance(begin(values), std::remove_if(begin(values), end(values), std::ref(clos))));

现场演示