| |
| Posted by Craig Black | PermalinkReply |
|
Craig Black
| Maybe I'm just missing something here, but I could never figure out why it is necessary to have classes and structs. The behavior of C++ classes and structs is almost identical. In C++ you can declare classes (or structs) to be allocated on the stack (auto) or on the heap (with new). C# has a different approach where structs are value types on the stack and classes are reference types. If I understand correctly, D does something similar to C#. Correct me if I am wrong.
IMHO, the C# approach is not as good as the C++ approach (disregarding the fact that C++ "new" does not return a reference counted garbage-collected object). The reason is that C++ classes are more reusable than C# classes. If you want a data type to be used as a value type _and_ a reference type, you are required to declare both a class and a structure, whose contents are identical. We edumecated folks call this sort of thing code duplication. Thus a C++ class is more reusable than a C# class in this respect.
C#'s incorrect approach is a byproduct of its trying to be so much like Java, a language that does not support "value types".
/////////////////////////////////
C++ sytax.
stack variable:
ClassName variableName;
heap variable:
ClassName *varName = new ClassName;
//////////////////////////////////////
D syntax ?
I'm not sure I completely grasp the D's appraoch. Are D's heap objects reference counted objects? If I am not mistaken "raii" or "auto" allows the programmer to use classes as automatic variables. Correct me if I misunderstand.
stack variable:
auto ClassName varName = new ClassName;
heap variable ?reference counted?:
ClassName varName = new ClassName;
///////////////////////////////////////
My Proposition for D:
I propose we ditch the whole class, struct approach to reference and value
types.
I think we should allow classes to be either, but not with the above syntax.
Everything in Java is a reference type, so there was no need to say "This is
a reference." However, in a language that supports both reference and value
types, I believe we should use a different syntactical approach.
stack variable:
ClassName varName;
heap variable (reference counted):
ref ClassName varName = new ClassName;
-or-
ClassName& varName = new ClassName;
Thus, there is no need for an "raii" or "auto" keyword.
"struct" is also unnecessary, since a class can be a value or reference
type.
Also, it should not be necessary to differentiate between a reference and
value type function parameter. You should be able to pass in either one as
a parameter to a function or method.
This is because the language should automatically pass all objects by
reference anyway, since it is usually more efficient. However, in such a
situation an "in" parameter should not be allowed to be modified by a
function.
Please give me some feed back on this idea.
-Craig
|