为什么 *&x 与 x 不同?

Why is *&x not the same as x?

本文关键字:不同 为什么      更新时间:2023-10-16

简写:

下面的代码不能编译:

CComBSTR temp;
CMenu().GetMenuString(0,   temp, 0);

,但这是:

CComBSTR temp;
CMenu().GetMenuString(0, *&temp, 0);

为什么?


完整代码:

#include <atlbase.h>
extern CComModule _Module;
#include <atlapp.h>
#include <atlwin.h>
#include <atlctrls.h>
int main() {
    CComBSTR temp;
    CMenu().GetMenuString(0, *&temp, 0);
}

GetMenuString签名(from atluser.h, from WTL):

BOOL GetMenuString(UINT nIDItem, BSTR& bstrText, UINT nFlags) const;

因为一元运算符&*可以被重载,我猜CComBSTR可以。

* Update: *

对于那些想知道如何获得类型重载operator&的变量的地址的人来说,有TR1的std::addressof,以及为c++ 03兼容性提供的Boost实现。

CComBSTR可能重载了operator *operator &,以返回与GetMenuString()接收的参数类型匹配的类型

因此,虽然*&x与内置数据类型的x相同,但对于用户定义的类型可能不相同。

operator&CComBSTR上被重载并返回BSTR*,因此解引用它会给您所需的类型,即BSTR

如果没有编译,那么您应该有一个有意义的错误消息?

函数定义如下,需要BSTR&:

BOOL GetMenuString(UINT nIDItem, BSTR& bstrText, UINT nFlags) const

CComBSTR类本身不会强制转换为BSTR&,但是通过& operator* operator,它可以。

相关文章: