Monday, February 2, 2009

[C++] What's the difference between BSTR and _bstr_t?

I stumbled upon this recently while maintaining some old code where BSTR and _bstr_t were being used interchangeably. This was generating a nasty (to say the least) bug which you can read all about here.

The main thing to understand here is that BSTR is a dumb pointer while _bstr_t is a class that wraps BSTR. The difference between the two is pretty much the same between char* and std::string.

_bstr_t also works like a smart pointer, so it will free the allocated memory when the variable is destroyed or goes out of scope. Another thing to say is _bstr_t has reference counting, increased every time you pass the _bstr_t variable by value (avoiding unnecessary copy) and decrement when it is no longer in use. Whenever all references are destroyed, the allocated memory for the string is freed up.

More about _bstr_t here, more about BSTR here.

That's it folks - lousy as ever.

2 comments:

Anonymous said...

Johnny for MVP!

Unknown said...

I already am an MVB (where 'B' stands for Butcher) - why would I want to be an MVP? :-)