Reading about D: few questions

bearophile bearophileHUGS at lycos.com
Fri Dec 23 11:51:06 PST 2011


Mr. Anonymous:

> With the given example of: byte[1024] buffer = void;
> 
> So does the GC really scan this byte array?

The current D GC is not precise, so I think the current DMD+GC scan this array. Future better compilers/runtimes probably will be able to avoid it (with a shadow stack the gives precise typing information at runtime, used by a precise GC).


> The solution works but is not as clean as just using array ~= c;
> Is there any way (language, runtime, or phobos) to declare an array that 
> would reallocate memory by chunks, which are multiple of x?

Appending to built-in D arrays is several times slower than doing the same thing to a C++ vector, but in many situations the performance is enough. When it's not enough there is the "capacity" function in the object module. Or for even better performance the appender in std.array, that gives performance just a little worse than the C++ vector push back.


> Is there any use for const when defining variables?
> As I see it, there is no use for using e.g. const int x;, as it can't be 
> modified anyway;

const int x = 5 + foo(y) * bax(z);

It's better to use immutable or const everywhere this is possible and doesn't give you too many problems. In my D2 code about 70-90% of variables are now const or better immutable. This avoids some bugs and will help future compilers optimize code better.



> 5. Align attribute.
> 
> http://dlang.org/attribute.html#align
> 
> struct S {
>    align(4) byte a; // placed at offset 0
>    align(4) byte b; // placed at offset 1
> }
> 
> Explain this please.

I don't know. Keep in mind that DMD has many bugs, almost 50-100 gets removed every month.


> 6. Array slices manipulation.
> 
> a[] += 1; works but a[]++ doesn't.
> Not so important but just wondering: why, and is it intended?

It's a compiler bug. I think it's already in Bugzilla (but take a look in Bugzilla if you want to be sure).


> 7. Anonymous structs.
> In C you can write:
> 
> struct { int a; } s = {10};
> printf("%d\n", s.a);
> 
> In D you must declare the struct first:
> 
> struct S { int a; };
> S s = {10};
> writeln(s.a);
> 
> Why doesn't D allow anonymous structs?

D doesn't allow top-level anonymous structs.


> ++a[] works, but a[]++ doesn't.

Already known compiler bug.

----------------------------

Ali:

>There is nothing in the language that makes me say "the returned object is unique; you can cast it to mutable or immutable freely."<

The return value of strongly pure functions is implicitly castable to immutable.

And sometimes inout helps.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list