Suggestion: wrapping up value type objects

Kristian kjkilpi at gmail.com
Wed Oct 25 02:45:00 PDT 2006


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. 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();


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


Benefits:
- There is a standard way to dublicate objects, making programs more  
consistent, easier to read/write, and (thus) bug free.
- The number of operator functions are reduced almost to one third! (No  
need to implement 'opXxx's and 'opXxx_r's.)
- No more unnecessary temporaries.
- Value type objects are indeed part of the language. Note that they don't  
take anything away from normal reference types.



More information about the Digitalmars-d mailing list