Obsecure problem 1
Salih Dincer
salihdb at hotmail.com
Sun Jul 31 16:11:48 UTC 2022
On Sunday, 31 July 2022 at 14:52:03 UTC, FeepingCreature wrote:
> Note sure if I'm misunderstanding, but: D does not copy strings
> on value passing, because they're inherently reference types.
>
> You can think of a string (or any array) as a `struct { size_t
> length; T* ptr; }` combined with a bunch of syntax magic.
You got it right, but I didn't explain it right. I think you are
right. How could I forget! String is actually a struct, embedded
in the language. For example, it has members like .dub, .ptr,
capacity and .length (get/set).
Of course we should get a copy with .dub to avoid side effects.
But now that I've tested it, I haven't seen a problem with
split() and sort() . Okay, yes sort() can have side effects, for
example nums is affected by this. I also had to use to!(dchar[])
because of the UTF:
```d
auto sortStr(string E)(string str) {
import std.algorithm, std.conv;
return str.to!(dchar[]).sort!E;
}
auto splitStr(string E)(string str) {
import std.string;
return str.split!string(E);
}
auto sortArray(T)(T[] arr)
{
import std.algorithm;
return arr.sort;
}
void main()
{
import std.stdio : writeln;
string test = "alphabet";
auto nums = [ 1, 9, 4, 0, 3 ];
test.sortStr!"a > b".writeln;
assert(test == "alphabet");
test.splitStr!"a".writeln;
assert(test == "alphabet");
test.sortStr!"a < b".writeln;
assert(test == "alphabet");
nums.sortArray.writeln;
assert(nums == [0, 1, 3, 4, 9]);
}
/* Prints:
tplhebaa
["", "lph", "bet"]
aabehlpt
[0, 1, 3, 4, 9]
*/
```
In conclusion, one has to be careful, but D is a reliable
language.
SDB at 79
More information about the Digitalmars-d-learn
mailing list