Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stl map: issues with BSTR

Tags:

c++

stl

winapi

bstr

I use a map in my code <BSTR,struct> bstr being the key and struct the value.

Will this work or do I have to redefine something?

I see no compile issues and I'm able to add elements too. However, map.find() does not work. Even though the element is present, it always returns map.end() (element not found).

I did a temporary workaround as follows - by looping from map.begin() to map.end() and doing a lstrcmpW for each element. This seems to work, but dont think this is too efficient.

Any suggestions/tips on what could be wrong? Is it ok to use BSTR as key for a map? I know maps do not support some of the non-native data types - structs or classes...u need to define a < operator for that.

like image 696
Omi Avatar asked Nov 30 '25 20:11

Omi


2 Answers

Use ATL's CComBSTR as the key type instead of BSTR. CComBSTR overloads operator< to do actual string comparisson, rather than pointer (address) comparisson as you are currently doing.

CComBSTR also simplifies lifetime management. Using BSTR as the key type, you have to make sure that the BSTRs outlive the lifetime of the map (actually they have to be deallocated right before the map is destructed). CComBSTR follows the RAII principle so you don't have to do any manual deallocation.

like image 165
user1610015 Avatar answered Dec 02 '25 08:12

user1610015


BSTR type in C++ is a pointer. Map is comparing the pointers to each other and not the string. To use in map you should probably write a wrapper for BSTR or use a premade wrapper.

like image 27
John Bandela Avatar answered Dec 02 '25 10:12

John Bandela



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!