Old problem with performance
Rainer Deyke
rainerd at eldwood.com
Thu Feb 12 00:10:56 PST 2009
Christopher Wright wrote:
>> - I would even say that the reference type classes in D lead to more
>> problems. It is very easy for two objects in D to accidentally share
>> internal state, something that is impossible with value types.
>
> struct A
> {
> int* i;
> }
>
> A a, b;
> int* i = new int;
> a.i = i;
> b.i = i;
>
> Hey look, they share internal state!
That's not accidental. You did that on purpose.
> What mechanism for sharing state is available to by-reference objects
> but not by-value objects?
struct C {
T t;
}
C c1;
C c2 = c1;
If T was a reference type, 'c1' and 'c2' now share state, and it's up to
the programmer to write code to prevent this. Moreover, the D language
doesn't even give a hint as to whether T or a reference type or a value
type. If T is a template parameter, it could be both.
What I'd really like to see is a hybrid of struct and class that has the
RAII and value semantics of a struct, but the polymorphism of classes.
polymorphic_struct A {
}
polymorphic_struct B : A {
}
{
B b;
A a = b; // Creates a true non-sliced copy of 'b'.
} // Destructors are called when the variables go out of scope.
At the implementation level, the objects could be placed on the heap
unless the compiler determines that this is not necessary. The goal is
not performance, but consistent value semantics throughout the language.
The alternative is to work backwards and create a wrapper for classes to
give them value semantics:
struct value_semantics(T) {
this(T v) {
this.value = v;
}
this(this) {
this.value = this.value.dup;
}
~this() {
delete this.v;
}
T opDot() {
return this;
}
T value;
}
--
Rainer Deyke - rainerd at eldwood.com
More information about the Digitalmars-d
mailing list