Why there are no 'physical' object variables (only references)?

Sean Kelly sean at f4.ca
Sun Sep 10 08:59:34 PDT 2006


Kristian wrote:
> I'm used for having both the variable types, 'physical' and 
> reference(/pointer) ones, so it feels strange to work with D (or Java, 
> etc) that have reference types only.
> 
> First, there is no way to copy/clone an object (in general). That is, 
> unless you provide a copy/clone function (for all the classes you're 
> using).

Yup.  The .dup property is pretty standard, but there's no convention 
for whether this should represent deep or shallow copy (though shallow 
seems to make more sense).

 > Second, you cannot create classes that behave like basic types,
> e.g. like integers.

True.  You can get pretty close, but D does not support an assignment 
operator and there is no universal construction syntax as there is in 
C++.  This was a deliberate decision, as handling copyable objects in 
C++ is a common source of bugs.

> For example, in C++ you could have:
> 
> void func() {
>     Coord a, b, c;
> 
>     a.set(1, 2);
>     b.set(5, 10);
>     c = a + b;  //'c' is (6, 12)
>     b = c;
>     b.setX(2);  //'c' is unchanged, 'b' is (2, 12)
> }
> 
> The 'Coord' objects have no 'global meaning' here, they are just simple 
> values used in calculations. (So there is no need to reference them from 
> other parts of the code.)
> 
> I think it's a big restriction if a language does not have both the 
> variable types (physical + references).
> Why D and other similar languages have no physical types?

Currently, you can use a struct or construct a class in place using 
alloca.  Eventually, we will get a stack allocation syntax for classes 
along the lines of:

     Coord a = Coord(); // note there is no 'new'

I also proposed an '.isizeof' property to return the instance size of a 
reference/pointer at compile-time, but there was little interest in the 
idea.  However, it would allow you to do things like this:

     byte[Coord.isizeof] buf; // assume buf is properly aligned
     Coord a = new(&buf[0]) Coord();

> And, I hope that D will have a 'const' type specifier in the future. Now 
> you cannot know if a function will modify an object that is passed to it 
> as a parameter. Or if a member function of a class will change the 
> internal status of the object.

Don't we all.  But wanting it and coming up with a solid proposal for 
how it should work are entirely different issues, unfortunately.


Sean



More information about the Digitalmars-d mailing list