This syntax regarding null checking baffles me

kdevel kdevel at vogtner.de
Sun Jan 10 17:28:42 UTC 2021


On Sunday, 10 January 2021 at 16:44:29 UTC, Paul Backus wrote:

[...]

> Your opCast has the wrong signature.

"Wrong" in what respect?

> It should be:
>
>     bool opCast(T : bool)()

"My" opCast works as expected:

```null2.d
import std.stdio: writeln;
class C {
    int i;
    bool opCast ()
    {
       __PRETTY_FUNCTION__.writeln;
       return true;
    }
}

void bar (C c)
{
    if (c) writeln (3);
    else writeln (2);
}

void foo (ref C c)
{
    if (c) writeln (5);
    else writeln (4);
}

void main ()
{
    C c = new C;
    writeln (c);
    if (c) writeln (1);
    else writeln (0);
    bar (c);
    foo (c);
    cast (bool) c; // print bool null2.C.opCast()
    c = null;
    cast (bool) c; // Segmentation fault
}
```

$  dmd null2 && ./null2
null2.C
1
3
5
bool null2.C.opCast()
Segmentation fault




More information about the Digitalmars-d mailing list