Eliminate class allocators and deallocators?
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Wed Oct 7 17:11:31 PDT 2009
Michel Fortin wrote:
> On 2009-10-07 17:53:21 -0400, Craig Black <cblack at ara.com> said:
>
>>> Yes, recycling is best and I'm considering it. I'm only worried about
>>> the extra cost.
>>>
>>> Andrei
>>
>> No this is a bad idea. Removing the possibility to delete data will
>> cause serious problems with heap fragmentation in some programs.
>
> Hum, perhaps we need to review more thoroughly how memory allocation
> works. As Andrei said himself, we now have all the necessary parts in
> the language to reimplement 'new' as a library function.
>
> So let's say we ditch 'new' and 'delete' as keywords. Let's first
> replace the keyword 'new' with a static function of the same name in a
> class or a struct. It could be implemented this way:
>
> static T new(A...)(A a) {
> T t = GC.alloc!T(); // GC.alloc sets the T.init bits.
> t.__ctor(a);
> return t;
> }
>
> Usage:
>
> Foo foo = Foo.new();
>
> That's a static function template that needs to be reimplemented for
> every subclass (Andrei already proposed such kind of mixins) and that
> returns a garbage-collected object reference. Now, if you want manual
> allocation:
>
> static T new(A...)(A a) {
> T t = GC.allocNoCollect!T(); // GC won't collect this bit.
> t.__ctor(a);
> return t;
> }
>
> void dispose() {
> this.__dtor();
> GC.free(this);
> }
>
> Usage:
>
> Foo foo = Foo.new();
> ...
> foo.dispose();
>
> But then you could do much better: 'new' could return a different type:
> a smart reference-counted pointer struct for instance. The possibilities
> are endless.
>
That's just awesome. Incidentally it would dovetail nicely with the code
injection feature that I recently discussed here. But then that
increases the size of the language...
Andrei
More information about the Digitalmars-d
mailing list