'new' class method
Bill Baxter
wbaxter at gmail.com
Thu Oct 23 05:17:49 PDT 2008
On Thu, Oct 23, 2008 at 8:47 PM, Yigal Chripun <yigal100 at gmail.com> wrote:
> Bill Baxter wrote:
>> On Thu, Oct 23, 2008 at 6:32 PM, bearophile
>> <bearophileHUGS at lycos.com> wrote:
>>> In Python to create new instances of a class you use the normal
>>> function call syntax, this allows you to use them as factory
>>> functions:
>>>
>>> class C: def __init__(self, id): self.id = id def __repr__(self):
>>> return "<%s>" % self.id seq = map(C, [1, -5, 10, 3])
>>>
>>> That creates an array (list) of four objects.
>>>
>>> In D with a map() you can do something similar:
>>>
>>> import d.all; import std.string: format;
>>>
>>> class C { int id; this(int id) { this.id = id; } string toString()
>>> { return format("<%s>", this.id); } static C opCall(int id) {
>>> return new C(id); } } void main() { auto seq = map((int id){return
>>> new C(id);}, [1, -5, 10, 3]); putr(seq); }
>>>
>>> You can use the opCall method in a more direct way:
>>>
>>> auto seq2 = map(&(C.opCall), [1, -5, 10, 3]); putr(seq2);
>>>
>>> But probably even better is to replace the current new syntax with
>>> a class method that creates the instances (I think the Ruby
>>> language has such syntax):
>>>
>>> auto seq3 = map(C.new, [1, -5, 10, 3]); putr(seq3);
>>
>> That would be map(&(C.new), [1,-5,10,3]); wouldn't it?
>>
>>> With that normal code like:
>>>
>>> new Foo(10, 20)
>>>
>>> becomes:
>>>
>>> Foo.new(10, 20)
>>>
>>> Not a big change but allows a more functional style of coding.
>>
>> I like it. Can we get rid of delete's specialness too?
>>
>> Maybe just delete(anInstance); Make it like a normal function too.
>> Enabling things like
>>
>> map(&delete, [obj1, obj2, obj3])
>>
>> --bb
>
> Andrei already mentioned that he wants to get read of new/delete IIRC.
> I like Ruby's way of making it regular methods. something like:
> obj.new(..) and obj.delete()
> but, how do you specify stack vs heap allocation?
> something like:
> auto a = new S(); //on heap
> auto b = S(); //on stack
>
> also, what about placement new?
Hmm, I didn't realize D had a placement new. But clearly it does and
more -- you can pass args to new to control the allocator.
http://www.digitalmars.com/d/2.0/class.html
look for "Class Allocators".
also
http://www.digitalmars.com/d/2.0/memory.html#newdelete
So simply saying make it Obj.new(args) won't cut it. You need to be
able to do something like
Obj.new(newargs)(constructorargs)
also.
--bb
More information about the Digitalmars-d
mailing list