null this, classes, methods and "null this" assertion

Meta via Digitalmars-d digitalmars-d at puremagic.com
Fri Apr 10 19:19:50 PDT 2015


On Saturday, 11 April 2015 at 01:59:28 UTC, ketmar wrote:
> let's take a code like this:
>
> import std.stdio;
>
> class A {
>   size_t len = 42;
>   final size_t length () const { return (this !is null ? len : 
> 0); }
> }
>
> void main () {
>   A a;
>   writeln(a.length);
>   a = new A();
>   writeln(a.length);
> }
>
> in "-release" mode this code outputs "0" and "42", as expected 
> (by me).
> but without "-release" is raises "null this" assertion.
>
> while such check *may* be useful, it actually does nothing at 
> all for
> virtual functions (if we'll remove `final` from `length`, we'll 
> get
> segfault), and prevents writing non-virtual functions that can 
> do
> something sane for "null objects".
>
> my example with `length` actually has sense, as it mimicking 
> the built-in
> array behavior. instead of writing
>
>   if (obj !is null && obj.length > 0)
>
> i can simply write:
>
>   if (obj.length > 0)
>
> yet there is no way to tell the compiler (and this assert is 
> generated by
> the compiler) to not generate the assert for given method.
>
> i see that assert as completely unnecessary:
> 1. it does nothing to protect me from calling virtual method 
> with null
> object.
> 2. it forces me to write unnecessary null checks everywhere in 
> my code
> instead of delegating that to class methods.
>
>
> we can add another attribute that turns off such checks, but i'm
> proposing to remove that check altogether, cause:
> 1. there are too many attributes already.
> 2. let non-virtual methods segfaults as virtual ones already 
> does, thus
> making 'em consistent.
>
>
> please, kill that counter-productive limiting "feature" for 
> good!

As an aside, you could easily make length a UFCS function that 
avoids the null check.


More information about the Digitalmars-d mailing list