Calling members of null pointers-to-struct
Tor Myklebust
tmyklebu at csclub.uwaterloo.ca
Mon May 7 10:20:37 PDT 2007
Daniel Keep <daniel.keep.lists at gmail.com> wrote:
>
>
> Tor Myklebust wrote:
> > [...] (I still see no
> > earthly reason why it *should* be invalid for nonvirtual functions ---
> > by extension, I see no earthly reason why it should be invalid for
> > methods in D structs.)
> >
> > Tor Myklebust
>
> I suppose one could argue that if it is allowable to call the method
> with a non-existent instance for context, then there's no reason for
> making it a member function in the first place.
>
> Conversely, the vast majority of member functions are member functions
> specifically *because* they require the context to be there, where the
> assertion makes sense to have.
It doesn't make sense, though, which was precisely the point of the
original post. I even gave an example demonstrating why it doesn't make
sense; it is reproduced below:
struct list {
list *next;
int data;
static list *make(list *foo, int bar) {
list *x = new list();
x.next = foo; x.data = bar;
return x;
}
list *put(int k) {
return make(this, k);
}
bool has(int k) {
if (this == null) return false;
return data == k || next.has(k);
}
}
void main() {
list *foo;
foo = foo.put(42);
foo = foo.put(17);
foo = foo.put(31345);
assert(foo.has(42));
assert(foo.has(17));
assert(foo.has(31345));
assert(!foo.has(24));
}
This is a toy implementation of a linked list representing a set of
ints. The empty list is represented by a null pointer. A nonempty list
is represented by a null-terminated, er, list of struct lists.
It makes sense for put() to be a member function because put() needs to
know what 'this' is. It doesn't need to know about any of the members
of 'this', though, so it doesn't need to dereference 'this'. It also
makes sense for 'has' to be a member function, since it needs to know
about 'data' and 'has'. (Neither one is needed if 'this' is null,
however, since null represents the empty list and the empty list
contains nothing.) Thus, in neither method does it make sense for a
not-null assertion to be made but in both methods the context provided
by 'this' is required.
Tor Myklebust
More information about the Digitalmars-d
mailing list