我有以下课程:
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
is 1
- MyClass::operator bool()
被调用,它返回true
其转换为1
。所以我没有传递地址而是传递1
into SendMessage()
这会导致未定义的行为。
但为什么是operator bool()
首先调用?
这是使用 bool 运算符的已知陷阱之一,这是 C 继承的余震。阅读有关以下内容的内容绝对会让您受益匪浅安全布尔习语.
一般来说,您没有提供任何其他可匹配的转换运算符,并且 bool (不幸的是)被视为算术转换的良好来源。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)