sha*_*oth 2 c++ casting operators visual-c++
我有以下课程:
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;
};
Run Code Online (Sandbox Code Playgroud)
这是使用具有以下typedef的Microsoft SDK编译的:
typedef long LONG_PTR;
typedef LONG_PTR LPARAM;
Run Code Online (Sandbox Code Playgroud)
调用代码执行以下操作:
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 );
Run Code Online (Sandbox Code Playgroud)
突然castResult
被1
- MyClass::operator bool()
被调用,它返回true
被转换为1
.因此,而不是传递我传递1
到的地址SendMessage()
导致未定义的行为.
但是为什么operator bool()
首先要调用它?
Kor*_*icz 11
这是使用operator bool的已知陷阱之一,这是C继承的余震.阅读有关Safe Bool Idiom的文章,你肯定会受益匪浅.
通常,您没有提供任何其他匹配的铸造操作符,并且bool(不幸的是)被视为算术铸造的良好来源.
operator bool
是最佳匹配,因为如果没有显式强制转换char*
,void*
则无法转换为:long
bool
long L1 = (void*)instance; // error
long L2 = (char*)instance; // error
long L3 = (bool)instance; // ok
Run Code Online (Sandbox Code Playgroud)