I have a question about strings or specifically about the memory used by a string. I'm using MSVC2010. Consider this piece of code:
void Test() {
LPWCSTR String = L"Testing";
PrintString(String);
}
void PrintString(LPWCSTR String) {
// print String to console or similar
}
Is it safe to create and use a string in this way? Is the memory allocated for the storage of the string freed when the string goes out of scope?
Yes it is safe, but actually there are no allocations ;)
The L"Testing" will be kept in read only part of your exe file (as a constant set of characters). LPWCSTR String is just a pointer to it, and it doesn't need to be destroyed/deallocated
I'll assume that LPWCSTR
is typo for LPCWSTR
; a freaky Microsoft name for a pointer to a C-style string. It stands for "long pointer to constant wide string", and is an obfuscated way of writing const wchar_t*
.
Is it safe to create and use a string in this way?
Like any pointer, it's safe to use as long as it points to a valid array. In this case, it points to a string literal, which is an array with a lifetime as long as the program. So this usage is safe.
If it were to point to an array that might be destroyed while the pointer were still in use, then it would not be safe.
Is the memory allocated for the storage of the string freed when the string goes out of scope?
No; the pointer will not manage memory for you. If you need to do that, use std::wstring
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With