www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 3926] New: opCast(bool) in classes is bug-prone


           Summary: opCast(bool) in classes is bug-prone
           Product: D
           Version: 2.041
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: normal
          Priority: P2
         Component: DMD
        AssignedTo: nobody puremagic.com
        ReportedBy: bearophile_hugs eml.cc

--- Comment #0 from bearophile_hugs eml.cc 2010-03-10 08:01:15 PST ---
A opCast(bool) operator present in struct is called automatically in a if(x),
but the same is not true if x is a class.

So for example if you modify your code changing a struct into a class, other
parts of the program will silently stop working (it usually return true if the
class reference is not null). This is a problem, because it's bug-prone.

This shows the situation:

import std.stdio: writeln;

struct FooStruct {
    int x;
    T opCast(T:bool)() {
        return this.x != 0;

class FooClass {
    int x;
    this(int xx) { this.x = xx; }
    static FooClass opCall(int xx) { return new FooClass(xx); }
    T opCast(T:bool)() {
        return this.x != 0;

void main() {
    enum int N = 0;

    auto fstruct = FooStruct(N);
    if (fstruct)
        writeln("fstruct true");
        writeln("fstruct false"); // fstruct false

    auto fclass = FooClass(N);
    if (fclass)
        writeln("fclass true"); // fclass true
        writeln("fclass false");

    if (cast(bool)fclass)
        writeln("fclass true");
        writeln("fclass false"); // fclass false

A possible simple solution is to selectively disallow opCast(bool) for classes.
So an hypothetical conversion of a struct to a class raises a compile time
error that helps avoid bugs. But this makes it impossible to have cast(bool) on
classes. I don't know how often a cast(bool) can be useful in a class (probably
not often).

Another possible solution is to keep allowing cast(bool) in classes, but have
if(fclass) call opCast(bool) for classes too, avoiding the asymmetry between
structs and classes. But this requires to write if(fclass is null) to test the
value of the object reference.

This problem has to be faced soon, because later it will become impossible to

Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Mar 10 2010