R – Why doesn’t COM use a static empty BSTR

bstrcomstring

When allocating an empty BSTR, either by SysAllocString(L"") or by SysAllocStringLen(str, 0) you always get a new BSTR (at least by the test I made). BSTRs aren't typically shared (like Java/.NET interment) since they are mutable but an empty string is, for all intents and purposes, immutable.

My question (at long last) is why doesn't COM use the trivial optimization of always returning the same string when creating an empty BSTR (and ignoring it in SysFreeString)? Is there a compelling reason not to do so (because my reasoning is flawed) or is it just that it wasn't thought to be important enough?

Best Answer

I can't speak about what's idiomatic in COM, but in C++, Java, etc., there's an expectation that if you new an object, it will not compare equal (as far as address/object identity is concerned) to any other object. This property is useful when you use identity-based mapping, e.g., as keys in an IdentityHashMap in Java. For that reason, I don't think empty strings/objects should be an exception to this rule.

Well-written COM objects will allow you to pass NULL to a BSTR parameter and treat it as equivalent to an empty string. (This will not work with MSXML though, as I've learnt the hard way. :-P)

Related Topic