allocate array with new

Dmitry Olshansky dmitry.olsh at gmail.com
Tue May 15 05:36:27 PDT 2012


On 15.05.2012 16:27, Ondrej Pokorny wrote:
> 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
>
I thought in C++ RAII is about (i.e. even in C++ no heap allocation):
H h = H(5);

Same works in D. A call to clear  in you code above doesn't call 
destructor, it only zeros out pointer.
If you absolutely need pointers & heap and yet manual memory managment use:
clear(*h);


Explanation:
clear(x) calls x.__dtor if x is struct or class, then assigns
x = T.init;

A better way might be to just check if x.__dtor is callbale (thus 
pointer to sstruct will also work).

-- 
Dmitry Olshansky


More information about the Digitalmars-d-learn mailing list