为什么是“operator bool()”当我投射到“长”时调用 [英] Why is "operator bool()" invoked when I cast to "long"?

查看:121
本文介绍了为什么是“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编译的:

This is compiled with Microsoft SDK that has the following typedefs:

typedef long LONG_PTR;
typedef LONG_PTR LPARAM;

调用代码执行以下操作:

The calling code does the following:

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 。因此,不是传递地址,而是将 1 传递到 SendMessage(),导致未定义的行为。

Suddenly castResult is 1 - MyClass::operator bool() is invoked, it returns true which is converted to 1. So instead of passing the address I pass 1 into SendMessage() which leads to undefined behaviour.

但是为什么运算符bool()第一次调用?

But why is operator bool() invoked in the first place?

推荐答案

这是使用运算符bool的一个已知缺陷,这是C继承的余震。您最终可以从阅读安全Bool习语中受益。

It's one of the known pitfalls of using operator bool, that is a aftershock of C inheritance. You'd definitively benefit from reading about the Safe Bool Idiom.

一般来说,你没有提供任何其他匹配的转换操作符,bool(不幸的是)被视为一个好的算术铸造源。

In general, you didn't provide any other matchable casting operator, and bool (unfortunately) is treated as a good source for arithmetic casting.

这篇关于为什么是“operator bool()”当我投射到“长”时调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆