mardi 22 juin 2021

Is it valid to dereference this pointer in C++?

struct myclass {
    static const int invalid = -1;
    /*explicit*/ myclass(int i, double d = 0.0){
        _var = i
    }
    int var; 
    bool operator < (const myclass& rhs);
    bool operator == (const myclass& rhs);
    bool operator != (const myclass& rhs);
    bool operator > (const myclass& rhs);
    /*
    bool operator == (int rhs){
        return *(this) == myclass(rhs); // Is this valid C++ ?
    }
    */
};

int userCodeCall() {
    myclass m(10);
    
    // Valid use Case
    if(m != myclass::invalid) {
        //.... do something
    }
    
    // Invalid use case
    if(m < 0.5) { // I want this to give me a compiler error
        //.... do something
    }
}

I am working on a legacy codebase and I came across a class that can be implicitly constructed from int. And I found a bug where we were performing a < than comparison with a double. I thought of fixing this using an explicit with the constructor and then separately defining a == operation with an integer. But, I am not comfortable with the design. As I haven't seen this pattern anywhere else.

bool operator == (int rhs){
    return *(this) == myclass(rhs); // Is this valid C++ ?
}

I have two questions?

  1. Is it valid C++11/14/17?

  2. Can the design of the class be improved upon? Given I still want to have a "==" comparison style usage to stay valid as it is all over the user codebase.

    if(m != myclass::invalid) // some similar API need to be supported, if not the same.
    

Aucun commentaire:

Enregistrer un commentaire