<ns******@aol.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
What is the correct way to convert a const char* to a CString? I'm
somewhat of a newbie and have tried several ways. While they all
convert ok, I'm using a profiler that shows a memory leak for every
option. Here's what I have tried:
const char* test;
test = getMyChar();
//CString myCString((LPCTSTR)test);
//CString myCString(test);
CString myCString = new CString(test);
delete myCString;
Thanks in advance for your help
The CString class is, I believe, and MFC class, and not topical in this
newsgroup.
However, the problem most likely lies in the fact that you're making a call
to something called getMyChar(), which, I must assume (not seing its code),
allocates storage for the string. You probably need to recover THAT memory,
most likely by calling "delete [] test;". But not seeing the code for
getMyChar, I can't say for sure.
By the way, if that IS the way that getMyChar works, I see a couple problems
with it. First, its name implies that it gets a char, not a string. It
should say precisely what it does.
But more important, it's not the best practice to have allocation done
inside a function like that. It hides the fact that you need to do the
delete yourself.
A better method is to allocate the memory yourself, and pass the array (and
its length, to be safe) to a function which fills out the array for you.
Or, your function could work directly on a CString, instead of a char*
pointer.
Or, a better idea would be to use the RAII design. Look it up on Google for
more details.
Or, even better would be to use the std::string class instead of a char
array and CString.
-Howard