Question

Lately, I was working on a code and found following code:

CComBSTR userName;
SUCCEED(getUserName(userName));
if(userName == NULL) ...

The last line alerts me, since I'm comparing an object against NULL which is not intuitive. But after a glance on MSDN, it is perfectly supported:

bool operator ==( const CComBSTR& bstrSrc ) const throw( ); 
bool operator ==( LPCOLESTR pszSrc ) const; 
bool operator ==( LPCSTR pszSrc    ) const;     
bool operator ==(  int nNull  ) const throw( );

So my question is, why would API design of CComBSTR allow such a comparison? Just to be more tolerant to errors?

Was it helpful?

Solution

A smart pointer is designed and intended to mimic a raw pointer as much as possible, simply provide automatic memory management but otherwise be transparent to outside code. That means overriding the ->, =, and & operators, implementing conversion operations, etc. This way, the rest of the code can treat the smart pointer as if it were a real pointer in almost all aspects.

Imagine someone started with this code:

BSTR userName;
SUCCEED(getUserName(&userName));
if(userName == NULL) ...

Then wanted to upgrade to a smart pointer:

CComBSTR userName;
SUCCEED(getUserName(&userName));
if(userName == NULL) ...

See how that works? Only one line changed.

OTHER TIPS

First you should find the definition of the class CComBSTR to confirm whether you use the windows system API not your own method. When we develop COM, maybe your development system redefine the Class. when I use the API of the windows, there is no problem. good luck

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top