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.
std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
There is no functionality difference between string and std::string because they're the same type.
The code calls operator new[] to allocate memory for 10 string object, then call the default string constructor for each array element. In the way, when the delete operator is used on an array, it calls a destructor for each array element and then calls operator delete[] to deallocate the memory.
The std::string type is the main string datatype in standard C++ since 1998, but it was not always part of C++. From C, C++ inherited the convention of using null-terminated strings that are handled by a pointer to their first element, and a library of functions that manipulate such strings.
Does s.assign allocate a new buffer and copy the string into it or it assumes ownership of the pointer;
The STL string method assign
will 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.
If it copies, then what is the difference between assign and operator=?
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 assign
overloads.
If it doesn't copy, then does it free the memory or it is my responsibility?
No, the original pointer to the character array is still your responsibility.
It copies. The difference between assign and operator= is that you can specify the number of characters to be copied including null characters. The operator= just copies the c-string up to the first null byte.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With