I have some gaps in the understanding of string::assign method. Consider the following code:
char* c = new char[38];
strcpy(c, "All your base are belong to us!");
std::string s;
s.assign(c, 38);
Does s.assign allocate a new buffer and copy the string into it or it assumes ownership of the pointer; i.e. doesn’t allocate new memory and uses directly my address. If it copies, then what is the difference between assign and operator=? If it doesn’t copy, then does it free the memory or it is my responsibility?
Thank you.
The STL string method
assignwill copy the character array into the string. If the already allocated buffer inside the string is insufficient it will reallocate the memory internally. The STL string will not take ownership of the original array.Both ought to act in the same way, but there are a number of overloads to the STL assign method which give you more control over what happens. Take a look at this page for more information.
UPDATE: The MSDN has a number of examples of the various
assignoverloads.No, the original pointer to the character array is still your responsibility.