using D without GC

Andrea Fontana via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 8 03:04:04 PDT 2015


On Sunday, 7 June 2015 at 16:25:29 UTC, Oleg B wrote:
>> No just reserve some memory and preallocate the buffer you 
>> want before using it. It'll be a lot faster and cheaper.
> I know, it's only for test.
>
>> You shouldn't be using delete or new for that matter.
>> You should be using malloc + free. And emplace.
>
> auto myalloc(T)( size_t count )
> {
>     struct Impl{ size_t len; void* ptr; }
>     union Wrap { Impl impl; T[] arr; }
>     auto ret = Wrap( Impl( count, calloc( count, T.sizeof ) ) 
> ).arr;
>     enforce( ret.ptr !is null );
>     return ret;
> }
>
> class Bar
> {
>     float[] buf;
>     this() { buf = myalloc!float( 65536 ); }
>     ~this() { free(buf.ptr); }
> }
>
> For simple types arrays all clear. Emplace realization not 
> trivial for me yet. As I understand correctly it concerns 
> placing initial values of struct for example or values before 
> calling ctor in place to array segment without copying?
>
> But what I need use for class objects?
>
> class Foo
> {
>     Bar[] buf;
>
>     this()
>     {
>         buf = myalloc!Bar( 100 ); // I think it's ok
>         foreach( ref b; buf )
>             b = new Bar; // but calloc can't initialize class 
> correctly
>     }
>
>     ~this()
>     {
>         static if( gc_disable )
>         {
>             foreach( ref b; buf ) delete b;
>             free(buf.ptr);
>         }
>     }
> }
>
> Operator new automatically allocate range in GC-manage memory? 
> If it is whether is possible to change this behavior? It's 
> question relates to emplace too?

I guess you should follow andrei's post about new allocators!




More information about the Digitalmars-d-learn mailing list