c-为什么当我强制转换为“ long”时会调用“ operator bool()”?

我有以下课程:

class MyClass {
public:
   MyClass( char* what ) : controlled( what ) {}
   ~MyClass() { delete[] controlled; }
   operator char*() const { return controlled; }
   operator void*() const { return controlled; }
   operator bool() const { return controlled != 0; }

private:
   char* controlled;
};

这是使用具有以下typedef的Microsoft SDK进行编译的:

typedef long LONG_PTR;
typedef LONG_PTR LPARAM;

调用代码执行以下操作:

MyClass instance( new char[1000] );
LPARAM castResult = (LPARAM)instance;
// Then we send message intending to pass the address of the buffer inside MyClass
::SendMessage( window, message, wParam, castResult );

突然,castResult为1-调用MyClass :: operator bool(),它返回true并将其转换为1.因此,与其将地址传递给SendMessage()而不是将地址传递给1,这会导致未定义的行为.

但是,为什么首先要调用运算符bool()?

解决方法:

这是使用运算符bool的已知陷阱之一,这是C继承的余波.阅读有关Safe Bool Idiom的文章,绝对可以使您受益.

通常,您没有提供任何其他可匹配的强制转换运算符,并且bool(不幸的是)被视为算术强制转换的良好来源.

上一篇:检查c 11中是否存在运算符的最佳方法


下一篇:Java | =运算符问题