allocate array with new

Ondrej Pokorny pokorny.ondrej at gmail.com
Tue May 15 05:27:14 PDT 2012


On Tuesday, 15 May 2012 at 09:44:08 UTC, Jonathan M Davis wrote:
> On Tuesday, May 15, 2012 11:26:49 Namespace wrote:
>> On Tuesday, 15 May 2012 at 09:23:51 UTC, Kagamin wrote:
>> > Difference with what?
>> > new is a safe feature: it allocates in the GC heap
>> 
>> That's what i mean. So i have to delete it yourself with 
>> "delete
>> arr;", or not?
>
> No. _Never_ use delete. It's going to be deprecated. The GC 
> worries about
> freeing memory allocated on the GC heap, and new always 
> allocates on the GC
> heap. If you don't want to allocate on the GC heap, then use 
> malloc and free,
> in which case you _do_ need worry about freeing the memory.
>
> If you need to force destruction before the GC collects an 
> object, you can
> call clear on that object to have its destructor called and its 
> vtbl zeroed
> out, but it's memory still isn't freed. That's the GC's job.
>
> If you really have to, you can use core.memory to manipulate 
> the GC heap
> (including calling GC.free), but you really shouldn't be 
> messing with any of
> that unless you really need to and you know what you're doing.
>
> - Jonathan M Davis

Hi,
does this hold for structs too?

struct H
{
this(int a){writeln("ctor");}
~this(){writeln("dtor");}
};

...

H* h = new H(5);
clear(h);
...

output:

ctor

seems like destructor is not called.

if I change declaration of H to class H. output is following:

ctor
dtor

I tried to create object according to RAII idiom and in case of 
struct H my file handle remained open  and I was still able to 
write to file...

Ondrej



More information about the Digitalmars-d-learn mailing list