class allocators should be more encapsulated

Luís Marques luismarques at gmail.com
Fri Dec 29 04:19:04 PST 2006


Hello all.

I need to build a class for which there should be only one instance with 
a given attribute (of type char[]).

That can be provided by a class allocator with the following form:

     new (uint size, char[] data)
     {
         ...
     }

The same "data" must then also be a constructor parameter:

     this(char[] data)
     {
         this.data = data;
         ...
     }

Allocations then take the form:

new("my string") ClassType("my string");

That is problem #1, having to repeat the string. We could wrap this in a 
static method or in a template, but that takes away the point of a 
customized new: we are mostly back to the C++ method of having a private 
constructor and providing a factory method.

The problem #2 is repetition of calculations. All calculations that 
new() does cannot be stored in the instance, so this() has to perform 
them again. In my case, the data's hash is both computed on the new() 
(to check for an existing instance in an associative array) and on 
this() (to store it). Also, overloaded forms of new() and this() taking 
a dchar[] both have to converted the data to UTF-8 prior to calling the 
respective char[] variants;

Given this, I think a solution should be found to better encapsulate new().

Suggestion:

- forms of "new(...) Class(...)" are deprecated
- this() has to call the appropriate new() prior to accessing any of its 
members. Otherwise the default class allocator is called.
   - any arguments to new() are be passed to this() instead

E.g.

class Foo
{
     private int attr z;

     private new(uint size, int param)
     {
         ... allocate memory according to param
     }

     this(float bla, int param)
     {
         int x = param * 3;
         new(x);
         z = bla * param;
     }

     this(float bla)
     {
         // default allocator called
         z = cast(int) bla / 2;
     }
}

--
Luís Marques



More information about the Digitalmars-d mailing list