D needs emplacement new

anonymous via Digitalmars-d digitalmars-d at puremagic.com
Mon Apr 27 06:12:50 PDT 2015


On Monday, 27 April 2015 at 11:47:46 UTC, Namespace wrote:
> I create 1000 Foo's 1000 times. After the first iteration there 
> are 1000 unused Foo objects and the GC wants to reallocate 
> another 1000 Foo's. Now, what happen? The GC sees that the 
> previous 1000 objects are unused, remove them and allocate new 
> and fresh memory for the current 1000 Foo's? Or does the GC see 
> 1000 unused Foo's and reuse the memory?

Collected memory will be reused for new allocations. The GC won't 
necessarily reuse the exact memory of the 1000 old Foos for the 
1000 new Foos, but chances are it actually will.

> How can I observe if the later is true? If I store the pointer 
> to the object to compare them, the GC will recognize that and 
> will not finalize the object.

You can store the pointer as a size_t on the GC heap, and the GC 
will not regard it as a pointer. Alternatively, you can store it 
on the C heap, which is also ignored by the GC.

Using size_t:

----
void main()
{
     import std.stdio;
     import core.memory: GC;

     auto pointerInDisguise = new size_t;
     *pointerInDisguise = cast(size_t) cast(void*) new Object;

     /* Not sure why stomping is necessary, but without this, the 
first
     try below fails. */
     static void stomp() {ubyte[1024] x;}
     stomp();

     GC.collect();
     writeln(cast(size_t) cast(void*) new Object == 
*pointerInDisguise);
         /* prints "true" => memory is reused */

     GC.collect();
     writeln(cast(size_t) cast(void*) new Object == 
*pointerInDisguise);
         /* prints "true" => memory is reused */
}
----


More information about the Digitalmars-d mailing list