Hiding class pointers -- was it a good idea?

Bill Baxter dnewsgroup at billbaxter.com
Wed Aug 15 18:27:18 PDT 2007


Walter Bright wrote:
> Brad Roberts wrote:
>> On Wed, 15 Aug 2007, Walter Bright wrote:
>>
>>> Bill Baxter wrote:
>>>> I'm starting to seriously wonder if it was a good idea to hide the 
>>>> pointers
>>>> to classes.  It seemed kinda neat when I was first using D that I could
>>>> avoid typing *s all the time.  But as time wears on it's starting to 
>>>> seem
>>>> more like a liability.
>>> Having classes be by reference only has some serious advantages:
>>>
>>> 1) Classes are polymorphic and inheritable. By making them reference 
>>> only, the
>>> "slicing" problem inherent in C++ is completely and cleanly avoided.
>>>
>>> 2) You can't write a class in C++ without paying attention to assignment
>>> overloading and copy constructors. With classes as a reference type, 
>>> these
>>> issues are simply irrelevant.
>>
>> They're _less_ relevant.  There's still the valid usecase of acting 
>> like a value to avoid instance sharing where copy construction and 
>> assignment's are.  This is where it's the author of the class making 
>> that decision rather than the user that you talk about in other 
>> responses to this thread.
> 
> I strongly feel that for that usecase, one should be using a value type, 
> i.e. a struct, not a class. C++ classes are neither one nor the other, 
> thereby doing neither well.
> 
> 
>> That's the distinction between 'by value' vs 'by reference' and 'as a 
>> value' vs 'as references'.  IE, access vs behavior.  I like a strong 
>> enforcement and distinction between the access part, but I do believe 
>> that it should be possible for a class write to achieve value semantics.
> 
> I don't agree, I think there is much to be gained by drawing a strong 
> distinction. Value and reference types are *fundamentally* different. 
> Classes are an OOP type, and giving them value semantics introduces all 
> the gotchas C++ has with them (like the slicing problem).

The problem I see is that it's really not always clear whether a value 
or reference type is desired.  Currently I'm thinking about container 
classes.  Value semantics are convenient and efficient for small 
containers.  D's built-in containers are basically structs as is often 
pointed out.  If you create lots of little Sets here and there you don't 
want each Set to require two allocations (one for the object itself, and 
another for adding some content to it).  Only one allocation is really 
required there.  But you might also want your set to implement some 
interfaces (a la Tango).  Then you're forced into a class even though 
you don't particularly want anyone to subclass your Set.  And even 
though you'd rather use it primarily as a value type (for efficiency, 
plus since the intent is a 'final' class there will be no derived 
classes and thus there are no slicing issues).


--bb



More information about the Digitalmars-d mailing list