Quantcast
Channel: Visual C forum
Viewing all articles
Browse latest Browse all 15302

Casting CString to LPCWSTR,when I use the pointer,CString no longer exists.

$
0
0

I write code like this,


CString GetName()

{

  return L"MyName";

}

// The code using CString.

LPCWSTR myname = GetName();

MessageBoxW(0,myname,0,0);  //here myname is invalid because the returned CString got freed.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Of course I can use a variable to hold the returned CString,like below,

CString myname = GetName();

MessageBoxW(0,myname,0,0);

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

But sometimes I got an array of LPCWSTR to assign to,like below,

LPCWSTR names[5];

for(int i = 0; i < 5; i++)

{

  CString name = GetName();

  names[i] = name ;

}

PrintName(names,5);

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Now it is wrong again,the CString variable got freed again.

I have to keep an array of CString to make sure when I use the LPCWSTR,the corresponding CString still exists.

Any suggestion would be appreciated.

Thanks,



Viewing all articles
Browse latest Browse all 15302

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>