I am a java programmer and one day old to C/C++ programming. And I am attempting to create a std::string from char*
This is my character buffer -
char* token = (char*) malloc ((numberOfCharacters) * sizeof (char));
And this is how I create a std::string object -
std::string strKey (token);
But do I need to free 'token' after this call or the strKey
refers to character buffer pointed by token?
std::string
constructor makes a copy oftoken
, it doesn't take ownership of it. So yes, you have tofree()
it after buildingstrKey
.Anyway, you should use
new
anddelete
operators in C++ code:Don't use C
malloc
andfree
, unless you have a specific reason for doing so.