a more efficient use of BSTR?

This is a discussion on a more efficient use of BSTR? within the C++ Programming forums, part of the General Programming Boards category; <code>
TCHAR szBuf[14];
szBuf[0]=0;
wsprintf(szBuf, _T("some string, %d", i=1);
ComBSTR bstrName = (BSTR)szBuf;
</code>
It seems wrong to allocate space ...

Also, your wsprintf() will overflow the buffer szBuf - it generates 15 characters of data, counting the null terminator. (Also, you don't need to zero the first character - wsprintf() is just overwriting that.)

There. Now your program is not going to break if you change from unicode to MBCS. Do not worry about the fact that there is one buffer on the stack and another allocate from SysAllocString. This is normal when writing code such as we have here.

Last edited by iMalc; 02-12-2010 at 01:29 AM.
Reason: Fixed wrong function name on the print line

a more efficient use of BSTR?

Thanks, all.

I see no way, based on my reading, to get the parameter represented by the %d into the CComBSTR through a constructor call. In other words, it seems I must call some kind of wchar version of printf-type of function to get the %d guy returned and appended to the initializing character string.

There was nothing wrong with the function used in the original code. wsprintf != swprintf

Yes there absolutely was something wrong with using wsprintf. The code would needlessly fail to compile if the project settings were change from Unicode to Multi-Byte-Character-System.

You don't use TCHAR (which can be either characters size) and then explicitly use the wide char version of a function. You either use the TCHAR versions for all bits, or you use the WCHAR or CHAR versions for all bits.
It's just like using a char and then copying that into an int and expecting it to be negative if the high bit is set. Since a char can be unsigned, it might not do what you expect. You need to use the right data types, and functions taking those types, for the right job.

Yes there absolutely was something wrong with using wsprintf. The code would needlessly fail to compile if the project settings were change from Unicode to Multi-Byte-Character-System.

You don't use TCHAR (which can be either characters size) and then explicitly use the wide char version of a function. You either use the TCHAR versions for all bits, or you use the WCHAR or CHAR versions for all bits.
It's just like using a char and then copying that into an int and expecting it to be negative if the high bit is set. Since a char can be unsigned, it might not do what you expect. You need to use the right data types, and functions taking those types, for the right job.

But if you look at the declaration of wsprintf you'll see that it takes the arguments LPTSTR and LPCTSTR. Long Pointer to (Const) TCHAR String. So it's not wide-char specific, it depends on if UNICODE is defined or not.