I have a c++ class with a member that is a string, something like:
class Phone {
string name;
void foo()
{
name = string("new_name");
}
}
Now, within the function "foo", I reassign the string to "new_name". My question is:
newStr = erase( str , match ) deletes all occurrences of match in str . The erase function returns the remaining text as newStr .
C++ String erase() This function removes the characters as specified, reducing its length by one.
Yes, std::string
manages memory for you. (That's one of the reasons for its existence!) How it does that is an implementation detail (for example, it may use copy-on-write, reference counting, or deep copy semantics) but for the most part, std::string
will always correctly free the memory if it is not needed anymore.
Of course, this is assuming that there are no bugs in the implementation of the assignment operators or the destructor of std::string
(which is true for all classes that implement a non-default assignment operator/destructor).
If it's std::string
we're talking about then everything is correctly freed.
However, what exactly happens under the hood is up to the implementation. Several std::string implementations use some form of reference counting, so it's implementation dependent.
Also note, that your code does the same as:
name = "new_name";
... and even more explicitly:
name.assign( "new_name" );
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