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:

  1. 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?
  2. 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?
有帮助吗?

解决方案

  1. For queestion 1, you just give yourself the correct answer.

  2. And for question 2, it is just like question 1. You see, in the SetBob, the program allocates (you can consider it just like "malloc" ) a space for the string "Done", then set bob's pointer to the address of the string. So in this step, the memory belongs to the string is marked as "used", so even when it comes to the end of the function, it will never be destroyed. Only when you use "free", it will always in your memory.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top