www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Overloading new

I had this idea, but it didn't work. I figured that I might be able to have:

   auto MySecureAllocator mySecureAllocator = new MySecureAllocator();
   Int x = new Int(42); // not secure
   Int y = new(mySecureAllocator) Int(42); // secure;

The idea being that when mySecureAllocator goes out of scope, it can clean up the memory allocated to y, but leave x for the garbage collector. Alas that won't work. I just tried it out. The problem is that if you overload Int.new like this:
   class Int
   {
       new(uint n,MySecureAllocator m)
       {
           /* whatever */
       }
   }

then the normal, insecure constructor fails to compile. The error is:
    allocator new (uint n,MySecureAllocator m) does not match argument types
(uint)

Of course, I could overload that too, but then the GC would never get to look at it. So, it would seem that you can't have the same class being allocated in two different ways. You can't choose whether to allocate securely or insecurely. It's all or nothing. Bummer. Jill
Jun 09 2004