another compiler bug?

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Fri Jan 11 06:05:04 PST 2008


Aarti_pl wrote:
> torhu pisze:
>> Aarti_pl wrote:
[How to heap-allocate a class reference?]
>
> I managed to overcome bug in DMD with below:
> 
> void func(T)() {
>     static TYPE res;
>     res = new T;
>         return &res;
> }
> 
> although it will cause memory leaks for every type for which the 
> function is instantiated. So I consider bug in DMD as quite serious...

That will only allocate one reference per type (*not* per call to the 
function). Try this workaround instead:
-----
T* func(T)() {
     struct helper {
         T val;
     }
     return &(new helper).val;
}
-----
This heap-allocates a struct containing only a reference and returns a 
pointer to that member.


I don't think it's a bug in the compiler though, it behaves according to 
the spec. However, this seems to be an oversight in the spec as it 
doesn't provide for any way to directly allocate a "Class*".


More information about the Digitalmars-d-learn mailing list