A const BSTR isn’t

11 06 2012

If you’ve programmed any COM you’ve come across the ubiquitous BSTR string type. You may have even been tempted to have a read-only BSTR and used a const BSTR. Unfortunately this is not to be. If we look at WTypes.h we’ll see that BSTR is defined thus:

typedef OLECHAR* BSTR;

Basically a BSTR is a wchar_t*[1], but what happens when we try using a const BSTR?

The rule of thumb when trying to understand what is const in a C++ deceleration is to push the const as far as you can to the right without passing an asterisk and then read from right to left.

const int i; // int const i => i is a const-int 
const int *p; // int const * p => p is a pointer to a const-int
int * const q; // q is a const-pointer to int
const int * const pq; // int const * const pq => pq is a const-pointer to a const-int

This implies that const BSTR is the same as BSTR const, since the typedef captured the asterisk as part of the type the const can travel over it and produce a “wchar_t* const“, i.e.  the pointer is immutable, not the individual characters.

const BSTR deceptive = SysAllocString(L"Read only!");
deceptive[9] = '?'; // deceptive = "Read only?"
deceptive = NULL; // Compile error, deceptive is const

This is probably the exact opposite of the intended purpose.

The same translates to CComBSTR (and _bstr_t), having a const CComBSTR (and passing parameters by const reference) probably don’t do what you think they should.

The only advantage a const CComBSTR has is that it has static linkage but if that’s what you want you should just say static CComBSTR.

[1] At least at the static type level, at the semantic level it’s another story.




3 responses

12 06 2012
Assaf Lavie

COM??? Tag this post as paleoprogramming.. 🙂

12 06 2012
Motti Lanzkron

🙂 what can I say…. some code bases have history.

27 09 2012
Global BSTRs « I will not buy this blog, it is scratched!

[…] that precedes the actual string data. BSTRs also resist the concept of const correctness, you can’t have a const BSTR which can be a bit of a pain when you want to have BSTR […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: