[cfe-dev] error with lambda function that results in endless loop

Lars Viklund zao at acc.umu.se
Thu May 3 03:56:26 PDT 2012


On Thu, May 03, 2012 at 12:53:26PM +0300, Ran Regev wrote:
> 
> Colleagues,
> 
> While working with some c++11 features I have encountered a problem with std::sort;
> >From some reason it was stuck when I tried to sort more than 10 elements.
> 
> I simplified the code to use normal int, instead of my objects, and it gets stuck above 30 elements.
> 
> void checkSort( std::vector<int>& v )
> {
>     std::sort( v.begin(), v.end(),
>         [] (const int& a1, const int& a2) -> bool
>         {
>             return true;
>         }
>     );
> }
> Surly returning true regardless of the value of the elements has no real meaning and can results in nonsense like a1<a2==true && a2<a1==true
> And surly this is a bad idea to write code like this, but still - why it passes 30 and not 31?

The standard requires that the comparator shall provide a strict weak
ordering on the values. Your comparator doesn't and thus invokes UB.

Forever looping past a particular cutoff point is very valid undefined
behaviour. Some standard libraries are friendly enough to test whether
your comparator is broken or not in debug mode with a nice assert. This
one apparently isn't.

As for the hard cutoff, it's not unusual that implementations choose
between several different sorts depending on the size, the phase and
possibly the nature of the data.

-- 
Lars Viklund | zao at acc.umu.se



More information about the cfe-dev mailing list