Hiding class pointers -- was it a good idea?

Bill Baxter dnewsgroup at billbaxter.com
Fri Aug 17 12:49:39 PDT 2007


Russell Lewis wrote:
> Walter Bright wrote:
>> That's known as the 'slicing' problem. It's pernicious in that it can 
>> be extremely hard to expose via testing or code reviews, yet will 
>> expose the program to unpredictable behavior.
> 
> It frustrates me that people keep conflating what are orthogonal 
> questions, such as:
>   - Should we allow copy-assignments of class types?
>   - Should we allow classes on the stack?
>   - Should we use '*' to declare pointers-to-classes?
> 
> Those are 3 *VERY* different questions.  IMHO, we should disallow 
> copy-assignments of class types (compiler detects the problem and spits 
> out a clear error message, thus trivially educating the beginners), but 
> still require the '*'.

And I assume you would still allow classes on the stack in that case.
Good point.  That way you would retain uniform struct/class syntax, but 
still avoid the slicing problem.

The only down side I can think of is what someone mentioned before. 
Since you can't use operator overloading on pointers, it would mean either
1) you suffer through lots of dereferencing (*a + *b), or
2) you need to introduce a full-fledged C++-like reference type (a 
pointer that acts like a value).  Or
3) you require a sigil to do all pointer math.

More about 3):
I was tempted to to say "only for pointer-to-struct/class" but that 
interferes with the ability for class/struct to mimic built-in syntax. 
E.g. with this pattern:
    for (T* p=&TArray[0]; p!=end; p++) {...}
you don't want to have to do something different depending upon what T 
is.  With the approach 3) you'd have to make that something like
    for (T* p=&TArray[0]; p!=end; as_ptr(p)++) {...}

Maybe you could use # for the sigil instead of as_ptr().  It has an 
intuitive meaning of "treat this as a simple number" instead of 
something more complex:
    for (T* p=&TArray[0]; p!=end; #p++) {...}

That doesn't seem half bad to me, but it would certainly be annoying for 
code that does lots of pointer math.

--bb



More information about the Digitalmars-d mailing list