weird behave of Array?
dmm
dmm at test.com
Mon Jul 29 05:58:21 UTC 2019
On Sunday, 28 July 2019 at 17:45:16 UTC, Adam D. Ruppe wrote:
> On Sunday, 28 July 2019 at 17:21:25 UTC, dmm wrote:
>> test(str);
>
> The array is passed by value here, so changes to its ptr and
> length will not be seen outside the function.
>
> However, what goes *through* the pointer - which includes the
> contents and the capacity - will be seen. The runtime tries to
> minimize weird stuff by opting for making the capacity 0 if the
> array structure has been modified in a function (so of the
> length is changed, if it is appended, etc.), so then appends
> will not stomp over contents from two different locations.
> Since the memory pointed to is a shared resource it is
> conservative in not reusing it.
>
> You can read a bit more about this here
> https://dlang.org/articles/d-array-article.html#append-on
> (really the whole article might be good background).
So, d try to be smart, only make thing worse? the following code,
it keeping realloc when call reset. this won't happend in cpp if
call vector.resize under capacity.
import std.stdio : writefln;
class Lexer {
ubyte[] buf;
this() {
buf.reserve(1024);
writefln("%x, %d, %d", buf.ptr, buf.length, buf.capacity);
}
void doSomething() {
buf.length = 1024;
}
void reset() {
buf.length = 0;
writefln("%x, %d, %d", buf.ptr, buf.length, buf.capacity);
}
}
void main() {
Lexer l = new Lexer();
l.doSomething();
l.reset();
l.doSomething();
l.reset();
}
BTW, why call reserve(1024) got capacity at 1358? isn't
reserve(n) means capacity = length + n? how do you set capacity
to 2 ^ n?
More information about the Digitalmars-d-learn
mailing list