another compiler bug?

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Sun Jan 13 06:33:10 PST 2008


Marcin Kuszczak wrote:
> That leads me to discuss another bug which I discovered. 
> 
> Let's say we have program like below:
> --------
> import std.stdio;
> struct Pattern(T : bool) {
>     string beg = "test";
> }
> 
> Pattern!(T) get(T)() {
>     static Pattern!(T) pattern;
>     return pattern;
> }
> 
> void main() {
>     writefln(get!(bool).beg);
>     get!(bool).beg = "other";
>     writefln(get!(bool).beg);
> }
> --------
> 
> Above program prints:
> test
> test
> 
> although I would expect it will print:
> test
> other
> 
> It seems that memory reserved for struct in template function is initialized
> every time the function is executed.

No, it's just initialized once. However, the struct itself isn't 
returned; a *copy* of it is returned. That copy is what's modified by 
the assignment. The second call will return a fresh copy of the original 
(with "test" remaining the string value).

> This behaviour is different when we change Pattern to be class instead of
> struct. Then it is possible to create kind of singleton pattern for every
> type.

Yes, class instances are passed by reference, so the assignment would 
change the 'static' instance (assuming you 'new' it the first time 
around, so there is one).
The same effect should be observed if you change the function to:
-----
Pattern!(T)* get(T)() {
     static Pattern!(T) pattern;
     return &pattern;
}
-----
for the struct version (returning a pointer to the global instance 
instead of a copy of it).

> What do you think?
> 
> BTW. Where should I discuss bugs? I have another dozen of them and would
> like to discuss some of them before posting to bugzilla. Is it better to
> post to d.learn or d.bugs?

If they are of the same kind as this one, you may want to stick to 
d.learn as it's not actually a bug :P.
(Or at least, it's a bug in your code rather than in the compiler; the 
compiler does exactly what I'd expect it to do and what IMO it should do)


More information about the Digitalmars-d-learn mailing list