Why is sort allocating in this case?
Jack Stouffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Sep 17 19:21:09 PDT 2015
The docs explicitly say that SwapStrategy.unstable is
non-allocating, but this code (which is for finding the
statistical mode of a range) will fail to compile.
auto mode(alias pred = "a == b", R)(R r) @nogc
if (is(ElementType!R : real) &&
isInputRange!R &&
!isInfinite!R)
{
import core.stdc.stdlib : malloc;
import std.algorithm.iteration : group;
import std.algorithm.sorting : sort, SwapStrategy;
import std.algorithm.mutation : copy;
import std.typecons : Tuple;
alias LT = Tuple!(Unqual!(ElementType!R), size_t);
if (r.empty)
{
return real.nan;
}
auto grouping = r.group!pred;
// Because the struct Group does not have swappable elements,
it cannot be
// sorted, so copy it to another array
auto buffer = (cast(LT*) malloc(r.length * LT.sizeof))[0 ..
r.length];
copy(grouping, buffer);
sort!("a[1] > b[1]", SwapStrategy.unstable)(buffer);
return buffer[0][0];
}
$ dmd/src/dmd -unittest test.d
test.d(439): Error: @nogc function 'test.mode!("a == b",
int[]).mode' cannot call non- at nogc function
'std.algorithm.sorting.sort!("a[1] > b[1]", cast(SwapStrategy)0,
Tuple!(int, ulong)[]).sort'
More information about the Digitalmars-d-learn
mailing list