Range Redesign: Empty Ranges

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Mar 6 19:03:39 UTC 2024


On Wednesday, March 6, 2024 6:09:52 AM MST Ogi via Digitalmars-d wrote:
> On Wednesday, 6 March 2024 at 12:20:40 UTC, Atila Neves wrote:
> I thought I'd found a clever way to
>
> > make this work for classes but apparently this crashes, much to
> > my surprise:
> >
> > ```d
> > class Class {
> >
> >     bool empty() @safe @nogc pure nothrow scope const {
> >
> >         return this is null;
> >
> >     }
> >
> > }
> >
> > Class c;
> > assert(c.empty);
> > ```
>
> I’m surprised that the equivalent C++ code *doesn’t* crash (at
> least on my machine):
> ```
> Class* c = nullptr;
> assert(c->empty());
>
> That’s still UB though.

The issue is whether the function is virtual. In D, class member functions
are virtual by default, so you get a crash when the program attempts to use
the vtable to look the function up (and therefore attempts to dereference
null), whereas in C++, you don't, because class member functions are
non-virtual by default, and so it doesn't do anything with the vtable. If
you mark the function as final in D (without it overriding anything), then
there shouldn't be a crash, and if you mark the C++ function as virtual,
then there will be.

- Jonathan M Davis






More information about the Digitalmars-d mailing list