If you are absolutely sure that the content of the string will not be modified, you can cast the const
away via a static_cast
; a situation where this can be acceptable for example is if you are using some struct
to provide data to a function, but the same struct
is also used for retrieving it, so that member is LPWSTR
instead of just an LPCWSTR
.
If, on the contrary, the function to which you'll pass the struct
needs to modify the string, you have two alternatives.
The safest one is to allocate a separate copy of the string as a raw dynamic array of WCHAR
and copy there the content of the wstring
. You will probably want to wrap the result of the new
with a smart pointer, unless you're transferring the ownership of the string (and in that case you'll probably have to use some special allocation function).
You can also pass a pointer to the internal buffer of the string using &YourString[0]
, but (1) I'm not sure it's guaranteed to work by the standard, and (2) it works fine only if the function won't change the length of your string adding a L'\0'
before the end of it; in this case you should also re-adjust the actual length of the string.
Both in the last and in the first case you must be sure that the function you're passing the struct
to do not expect the pointed buffer to live longer than the scope of your wstring
(careful: mystream.str()
is a temporary that dies on the very line you use it, you have to assign it to a new variable to give it a broader scope).