Suggestion: wrapping up value type objects
Don Clugston
dac at nospam.com.au
Wed Oct 25 05:24:07 PDT 2006
Kristian wrote:
>
> I found it strange that D has no copy/clone operator, lets say 'opClone'.
>
> Before you say that there is a reason for it and D does not handle
> objects as value types (like C++ does), I have to point out that D
> already handles (or should handle) objects as value types in some
> situations. I'm talking about the 'opXxx' operators ('opAdd', 'opSub',
> etc).
>
> First I have to say that I'm not against using objects as reference
> types. But, sometimes it's necessary to create value types (out of
> classes), and using them could be easier than it's now.
>
>
> If a class has an 'opXxx' operator, then it normally returns a temporary
> object. Also the following should be true: 'a <op>= b' <-> 'a = a <op>
> b'. (Otherwise it would be a very rare case.)
>
> Dublication is needed when creating a temporary object (in 'opXxx'). So,
> why don't add the 'opClone' operator to the language? I mean, there
> already are 'opXxx' functions. Why don't standardize the way of creating
> copies/clones?
>
>
> Then you could get rid of all the 'opXxx' and 'opXxx_r' functions: they
> can be expressed by using 'opClone' and 'opXxxAssign' only.
Not necessarily. Consider Vector and Matrix.
Matrix a;
Matrix b;
Vector c;
a = b * c;
a = b.opClone().opMulAssign(c); // OK.
But
a = c * b;
a = c.opClone().opMulAssign(b);
// Oops -- we cloned the vector, should have cloned the matrix instead.
In fact, in general you cannot even assume that
(typeof(a*b) == typeof(a)) | (typeof(a*b) == typeof(b))
which means that cloning would sometimes create useless temporary objects.
That would
> also remove any unnecessary temporary objects from statements making
> calculations very efficient (as stated earlier). For example:
>
> a = (b * c) + d;
> ->
> a = b.opClone().opMulAssign(c).opAddAssign(d);
>
> And as mentioned in some earlier posts, you could also have binary and
> unary clone operators. E.g. (I use '<-' here):
>
> a <- b;
> ->
> a = b.opClone();
int a = 2;
int b = -3;
if (a<-b) { ... }
That particular one doesn't work. But := might be ok.
> The 'opClone()' function can also have a default implementation (done by
> the compiler). All the member variables are dublicated by default. For
> example:
>
> class Foo {
> int a;
> Bar b;
> }
>
> The default 'opClone' would then be (generated by the compiler):
>
> Foo opClone() {
> Foo ret = new Foo;
> ret.a = a;
> ret.b = b.opClone();
> return(ret);
> }
>
> If that's not wanted, or possible, then you can always implement the
> function by yourself, of course.
>
>
> Finally, there could also be easier way to create local objects (they
> too are discussed earlier in various posts). For example:
>
> Foo obj(); //a local object, already constructed
Currently, that compiles, and is equivalent to:
Foo function() obj;
More information about the Digitalmars-d
mailing list