New D technique - disable usage of "new" and "delete"

Basile B. b2.temp at gmx.com
Fri Jan 5 19:44:38 UTC 2018


I was chatting on IRC. One of the topic was about a "@nogc" 
thread. I suggested something like "core.thread.NoGcThread" that 
would take a "@nogc" function but then i realized that this 
hypothetical class could still be allocated on the GC heap.
So "new" and "delete" would have to be disabled...Despite of 
being deprecated it appears that class allocators and 
deallocators can be used for that purpose, without compiler 
changes:

---
class Foo
{
     @disable new (size_t size){return null;}
     @disable delete (void* p){}
}

void main()
{
     static assert(!__traits(compiles, new Foo));
     import std.experimental.allocator;
     import std.experimental.allocator.mallocator;

     auto f = make!Foo(Mallocator.instance);
     dispose(Mallocator.instance, f);

     // auto g = new Foo, // doesn't work
}
---

What's the point ?

- It's fun to discover that.
- Libraries that don't want their aggregates to reside on the GC 
heap can use this, with a mixin. (note: although the GCAllocator 
can still be used...)




More information about the Digitalmars-d mailing list