D safety! New Feature?
ag0aep6g via Digitalmars-d
digitalmars-d at puremagic.com
Tue Aug 2 22:44:42 PDT 2016
On 08/02/2016 11:48 PM, Mark Twain wrote:
> global ImmutableArray!int Data;
>
>
> MutableArray!int DataCopy = Data.Copy; // Creates a mutable copy of Data.
> ... Do work with DataCopy ...
> Data.Replace(DataCopy); // Makes a copy of DataCopy.
What benefit do ImmutableArray and MutableArray have over built-in
arrays? The thing above can be done with built-in arrays:
----
immutable(int)[] Data;
int[] DataCopy = Data.dup; // Creates a mutable copy of Data.
... Do work with DataCopy ...
Data = DataCopy.idup; // Makes a copy of DataCopy.
----
[...]
> void foo()
> {
> MutableArray!int Data;
> scope(Exit) Data.Reuse();
> }
>
> Reuse can simply mark the memory reusable rather then freeing it. This
> memory can then be reused the next time foo is called(or possibly use
> the stack for memory).
As far as I see, "marking for reuse" is practically the same as freeing
here. If Data were static, there could be a difference.
For built-in arrays, you can mark an array for reuse by setting the
length to 0 and calling assumeSafeAppend, like so:
----
void foo(int x)
{
static int[] Data;
scope(exit)
{
Data.length = 0;
Data.assumeSafeAppend();
}
Data ~= x;
import std.stdio: writeln;
writeln(Data, " ", Data.ptr);
}
void main()
{
foo(1);
foo(2);
}
----
More information about the Digitalmars-d
mailing list