gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:24:27 24 4
gpt4 key购买 nike

我有以下类(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com