Memory allocation of temporary lines

I have a question about strings, or specifically about the memory used by a string. I am 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 this way? Is the allocated memory for storing the string freed when the string goes out of scope?

+4
source share
5 answers

Yes, it is safe, but in fact there are no distributions;)

L "Testing" will only be stored in part of your exe file (as a constant character set). LPWCSTR String is just a pointer to it, and it does not need to be destroyed / freed

+7
source

I assume that LPWCSTR is a typo for LPCWSTR ; Microsoft's weird name for a C-style string pointer. It means "long pointer to a constant wide string" and is a confusing way to write const wchar_t* .

Is it safe to create and use a string this way?

Like any pointer, it is safe to use if it points to a valid array. In this case, it points to a string literal, which is an array with a lifespan while the program is. Therefore it is safe.

If it were pointing to an array that could be destroyed while the pointer is still in use, then it would be unsafe.

Is the allocated memory for storing the string freed when the string goes out of scope?

Not; a pointer will not manage memory for you. If you need to do this, use std::wstring .

+2
source

Yes, it is safe to use the string in this way. "Testing" will be stored in the data segment of your binary, and String will be initialized to point to it.

+1
source

L"Testing" is a wide string literal and has a static storage duration, which means that the lifetime is the lifetime of the program, you do not need to worry about releasing it. The C ++ draft of the standard in section 2.14.5 string literals in paragraph 11 read (emphasis mine):

A string literal that starts with L, for example L "asdf", is a wide String literal . A wide string literal is of type "array of n const wchar_t", where n is the size of the string, as defined below; static storage duration and is initialized with the specified characters.

0
source

Yes, it is safe.

An object is a string literal. This means that it has a program lifetime.

0
source

Source: https://habr.com/ru/post/1501525/


All Articles