Reputation: 125
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?
Upvotes: 4
Views: 448
Reputation: 158469
L"Testing"
is a wide string literal and has static storage duration which means it's lifetime is the lifetime of the program, you do not have to worry about deallocating it. The C++ draft standard in section 2.14.5
String literals paragraph 11 says (emphasis mine):
A string literal that begins with L, such as L"asdf", is a wide string literal. A wide string literal has type “array of n const wchar_t”, where n is the size of the string as defined below; it has static storage duration and is initialized with the given characters.
Upvotes: 0
Reputation: 254461
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
.
Upvotes: 2
Reputation: 14510
Yes it's safe.
The object is a string literal. It means that it has the lifetime of the program.
Upvotes: 0
Reputation: 1902
Yes, it is safe to use a string that way. "Testing" will be stored in the data segment of your binary and String will be initialized to point to it.
Upvotes: 1
Reputation: 4369
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
Upvotes: 7