Well, SysAllocString(), being a function, will take some CPU time to determine the BSTR given a char*, whereas just using L"asdf" will hard code it in there and should be faster. SysAllocString() also dynamically allocates memory, which is something you should avoid doing when you can.
It seems to me that both methods allocate memory. Looking in the debugger I can see that when you declare a BSTR it is an unitialized pointer and after using either method to assign a value to it, it is initialized.
I'm a bit surprised that the book I consulted (Developer's Workshop to COM and ATL 3.0 by Andrew W. Troelsen) only mentioned the SysAllocString() method in its section on BSTR.
The difference is whether it is using static or dynamic memory. Static is faster than dynamic, and using the L uses static. Even ignoring that, it is faster using L because the SysAllocString() must actually do some computation at run time to convert the char* to a BSTR (unless the optimizer gets this, and I don't think it does), whereas this is done at compile time using L.
is not entirely correct, because technically a BSTR is a length-prefixed (Pascal style) string, and L"" constructs a null-terminated (C style) string. The two are slightly different beasts.
By length-prefixed I mean the actual length of the string in bytes (18 in this case) is stored as an integer in memory just before the first character of the string.
If you were to pass this BSTR to any function that expects to find the length, it would probably crash. Also, performing this sort of assignment throws away the "const"-ness of the original string, which is bad form.
I am certainly not an expert on this, but as I understand it, a statement like
BSTR str = L"my string";
invokes the = operator for the BSTR class and calls the correct function to allocate memory and store the string in it with the length prepended. I have passed such a string to a function expecting a BSTR without problem. Anyone with more detailed knowledge is welcome to jump into the discussion.
A BSTR is not a class, it is just a typedef for LPWSTR. I didn't know that a BSTR was supposed to be a Pascal string, and if that is true then it shouldn't work where you are using it...
Actually it might work because a NULL character at the end of a BSTR is still allowed, even if not required. If present, you can treat the BSTR like a wide C-string. Still, be careful about passing it to functions that expect a true BSTR.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.