Why is “operator bool()” invoked when I cast to “long”?

后端 未结 3 433

I have the following class:

class MyClass {
public:
   MyClass( char* what ) : controlled( what ) {}
   ~MyClass() { delete[] controlled; }
   operator char*() c         


        
相关标签:
3条回答
  • 2021-01-22 00:19

    It's one of the known pitfalls of using operator bool, that is a aftershock of C inheritance. You'd definitively benefit from reading about the Safe Bool Idiom.

    In general, you didn't provide any other matchable casting operator, and bool (unfortunately) is treated as a good source for arithmetic casting.

    0 讨论(0)
  • 2021-01-22 00:27

    You cannot implicitly cast a T* to long. But you can cast a bool to long.

    So the operator bool is used.

    You have to define a operator LPARAM.

    0 讨论(0)
  • 2021-01-22 00:36

    operator bool is the best match, because char* and void* can't be converted to long without an explicit cast, unlike bool:

    long L1 = (void*)instance; // error
    long L2 = (char*)instance; // error
    long L3 = (bool)instance; // ok
    
    0 讨论(0)
提交回复
热议问题