Lambda 适用于最新的 Visual Studio,但不适用于其他地方
所以我写了一个讨厌的 lambda 来满足实现这个目标所需的最短代码量"问题:
So I've written a nasty lambda to satisfy a "shortest amount of code necessary to achieve this" question:
values.resize(distance(
begin(values),
remove_if(begin(values), end(values),
[i = 0U, it = cbegin(intervals), end = cend(intervals)](const auto&) mutable {
return it != end && ++i > it->first && (i <= it->second || (++it, true));
})
));
我的问题是,在 Visual Studio Community 2015 Update 3 版本 14.0.25425.01 上,这会输出所需的内容:
My problem is that on Visual Studio Community 2015 Update 3 version 14.0.25425.01 this outputs the desired:
4.2 9.1 2.3 0.6 6.4 3.6 1.4 7.5
4.2 9.1 2.3 0.6 6.4 3.6 1.4 7.5
但是在我尝试过的所有其他编译器上,我得到:
4.2 2.3 0.6 1.2 0.3 1.4 2.5 7.5
4.2 2.3 0.6 1.2 0.3 1.4 2.5 7.5
谁能告诉我是什么导致了不同的行为?
Can anyone tell me what's causing the different behavior?
推荐答案
您依赖于这样一个事实,即您传递给算法的确切闭包是用作谓词的闭包,但标准允许复制它:
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))));
现场演示
相关文章