I'm a bit rusty with C++ so I'm looking for help with a string pointer question.
First, let's consider some pointer basics with an integer:
void SetBob(int* pBob)
{
*pBob = 5;
}
int main(int argc, _TCHAR* argv[])
{
int bob = 0;
SetBob(&bob);
}
When run, main() creates an integer and passes its address to SetBob. In SetBob, the value (at the address pointed to by pBob) is set to 5. When SetBob returns, bob has a value of 5.
Now, let's consider a string constant:
typedef wchar_t WCHAR;
typedef const WCHAR *PCWSTR;
void SetBob(PCWSTR* bob)
{
*bob = L"Done";
}
int main(int argc, _TCHAR* argv[])
{
PCWSTR bob = L"";
SetBob(&bob);
}
When run, main() creates a PCWSTR, pointing to an empty string, and passes it address to SetBob. In SetBob, the PCWSTR pointer now points to a Done string. When SetBob returns, bob has a value of "Done".
My questions are:
- In a debugger, I see that the bob string is set to Done after calling SetBob. But why does this work? In the integer example, I allocated space for an integer so it makes sense that I could store a value in that space. But, in the string example, PCWSTR is just a pointer. Is the idea here that string constants are in memory too so I'm just pointing to that constant?
- Because the "Done" literal is within SetBob, do I have to worry that despite pointing to it, the memory for "Done" might be reclaimed? For instance, if I had created a WCHAR buffer, I'd be copying "Done" into the buffer so I wouldn't be concerned. But because I'm pointing to a literal within a function, might that literal be destroyed at some point after the function ends, leaving bob unexpectedly pointing to nothing?