'new' class method

dsimcha dsimcha at yahoo.com
Thu Oct 23 05:26:43 PDT 2008


== Quote from Yigal Chripun (yigal100 at gmail.com)'s article
> 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?

One thing I would definitely like to see is for struct and class syntax to be
unified so that if you change a struct to a class or vice versa, this doesn't
require changes all over your code.  Then again, the reference vs. value semantic
issue may bite you anyhow.



More information about the Digitalmars-d mailing list