Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string reassigned, is the old string correctly freed?

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:

  • What happens to the old, empty string? Is it correctly "freed"? Does it still occupy memory?
  • Now I initialize the string in the constructor of Phone to string("old_name"). Is this the same case as with the empty string before? What happens here to the old string "old_name"?
like image 644
Jan Rüegg Avatar asked Aug 30 '10 14:08

Jan Rüegg


People also ask

What does string erase Return?

newStr = erase( str , match ) deletes all occurrences of match in str . The erase function returns the remaining text as newStr .

What is erase in string?

C++ String erase() This function removes the characters as specified, reducing its length by one.


2 Answers

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).

like image 198
In silico Avatar answered Oct 02 '22 12:10

In silico


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" );
like image 28
Kornel Kisielewicz Avatar answered Oct 02 '22 11:10

Kornel Kisielewicz