user541686
user541686

Reputation: 210445

Why is *&x not the same as x?

Short version:

The following code doesn't compile:

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

but this does:

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

Why?


Full code:

#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 signature (from atluser.h, from WTL):

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

Upvotes: 8

Views: 444

Answers (4)

K-ballo
K-ballo

Reputation: 81349

Because the unary operators & and * can be overloaded, which I guess CComBSTR does.

* Update: *

For those who wonder how to get the address of a variable whose type has overloaded operator& there is TR1's std::addressof, and a Boost implementation of it for C++03 compatibility.

Upvotes: 11

Roman Ryltsov
Roman Ryltsov

Reputation: 69652

If it does not compile, then you should have a meaningful error message?

The function is defined as follows and wants BSTR&:

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

CComBSTR class does not cast to BSTR& itself, but through & operator followed by * operator it does.

Upvotes: 0

DeCaf
DeCaf

Reputation: 6096

operator& on CComBSTR is overloaded and returns a BSTR*, so dereferencing it gives you the type you need, i.e. a BSTR.

Upvotes: 4

Alok Save
Alok Save

Reputation: 206528

CComBSTR might have overloaded the operator * or operator & to return a type which matches the parameter type received by GetMenuString()

So while *&x is same as x for built-in data types, it may not be the same for user defined types.

Upvotes: 4

Related Questions