c++ - 为什么在我转换为 "operator bool()"时调用 "long"?

标签 c++ visual-c++ casting operators

我有以下类(class):

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;
};

这是使用具有以下类型定义的 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 );

突然 castResult1 - MyClass::operator bool() 被调用,它返回 true转换为 1。因此,我没有传递地址,而是将 1 传递给 SendMessage(),这会导致未定义的行为。

但为什么 operator bool() 首先被调用?

最佳答案

这是使用 operator bool 的已知陷阱之一,这是 C 继承的余震。您肯定会从阅读有关 Safe Bool Idiom 的内容中受益.

一般来说,您没有提供任何其他可匹配的转换运算符,并且 bool(不幸的是)被视为算术转换的良好来源。

关于c++ - 为什么在我转换为 "operator bool()"时调用 "long"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2145931/

相关文章:

c++ - 提升为命名空间中的自定义小部件

c++ - 良好做法 : construction of a complex member from a lambda

c++ - 使用 cout 从特定位置开始打印

c++ - "Mixing a dll boost library with a static runtime is a really bad idea..."

c - 为什么整数隐式转换为指针?

java - 将 long 转换为 double 并返回时值发生变化

c++ - 二叉搜索树,非递归使用堆栈

c++ - UE4Editor-CoreUObject触发断点

c++ - 循环依赖的问题

Delphi:泛型和 'is' - 运算符问题