class allocators should be more encapsulated

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Fri Dec 29 04:35:57 PST 2006


Luís Marques wrote:
> 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;
>         ...
>     }

I don't think that's what custom allocators were designed to do. They 
should only allocate some memory (and register it with the gc if necessary).

> 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.

Well, in D the factory method can be static opCall(), so allocation can 
look like this:
	ClassType("my string")
which looks a lot cleaner than the normal ClassType.create("my string").



More information about the Digitalmars-d mailing list