-
May 11th, 2010, 11:20 PM
#1
Cleaning up strings
Hi all,
Given this code, I want to make sure that there are no leaks from the strings that I have used:
#include <atlstr.h>
...
string varVarName = GetAttribute("VarIn", pNodeMap);
string stringIn = getDictionary(varVarName);
CString cstrIn = CString(stringIn.c_str());
cstrIn.Trim();
CT2CA pszConvertedAnsiString(cstrIn);
std::string strOut(pszConvertedAnsiString);
From what I understand, I think that I do not need to free std::strings as the program automatically frees those. I am not sure regarding CStrings, although I also believe that the program handles those.
What I know is that from the many string types in C++, only BSTR require freeing if you have called AllocSysString on it or equate it to NULL.
Can you help me understand why you need to free BSTR and not std::string, CString, etc.?
Thank you!
-
May 11th, 2010, 11:37 PM
#2
Re: Cleaning up strings
Originally Posted by LeanA
From what I understand, I think that I do not need to free std::strings as the program automatically frees those
Not quite. It isn't the program that frees the std::string, it's the std::string class itself that does the "freeing" when the variable goes out of scope. When the destructor of std::string is invoked, the memory that the std::string allocated is deallocated automatically.
I am not sure regarding CStrings, although I also believe that the program handles those.
Again, it isn't the "program" doing this -- it's CString's desctructor that does this.
What I know is that from the many string types in C++, only BSTR require freeing if you have called AllocSysString on it or equate it to NULL.
Well, this goes back to my earlier statements.
BSTR is not a C++ class, therefore it knows nothing by itself of when it goes out of scope or will not be used anymore.
Regards,
Paul McKenzie
-
May 12th, 2010, 01:19 AM
#3
Re: Cleaning up strings
Well, BSTR is not convenient enough to work with.
_bstr_t class (a wrapper of BSTR) is much better in use.
Victor Nijegorodov
-
May 13th, 2010, 08:45 PM
#4
Re: Cleaning up strings
Hi Paul, and Victor, thanks for replying.
Thankyou for those inputs! I'll keep them in mind.
Thank you very much!
-
May 14th, 2010, 07:08 AM
#5
Re: Cleaning up strings
Off topic to the question that you posed:
It looks like you are:
1) taking a std::string and converting it to a CString
2) trimming the CString
3) converting back to a std::string
Why not just trim the std::string directly ?
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|