Tutorial :Deleting string object in C++



Question:

I have a string object in my C++ program declared as follows:

string str;  

I have copied some data into it and done some operations. Now I want to delete the str object from the memory. I am not able to use delete operator since str is not a pointer. How do I delete that object from the memory to reclaim the memory allocated to it?

Thanks, Rakesh.


Solution:1

You don't have to. When the string goes out of scope, it's destructor will be called automatically and the memory will be freed.

If you want to clear the string right now (without waiting until it goes out of scope) just use str.clear().


Solution:2

str.clear();  

or

str = "";  

However, as stated in the comments, this does not guarantee (and, in fact, is rather unlikely) to actually return heap memory. Also not guaranteed to work, but in practice working well enough is the swap trick:

std::string().swap(str);  

Still, implementations employing the small string optimization will retain a few bytes of stack space (and str itself of course also lives on the stack).

In the end I agree with all comments saying that it is questionable why you want to do that. Ass soon as str goes out of scope, its data will be deleted automatically anyway:

{    std::string str;      // work with str    } // str and its data will be deleted automatically  


Solution:3

Add an Additional scope

{    String str;    ...    ...  }  

to ensure that str goes out of scope when you no longer need it. Remeber it could be tricky in terms of how other variables are also defined.


Solution:4

Now I want to delete the str object from the memory.

You can't. At least, you can't delete it completely. str is already allocated on stack (or in code segment if it is global variable), and it won't completely go away until you return from routine, leave the scope it has been created in (or until you exit the program - for global variable).

You can call .clear(), or assign empty string to it, but it doesn't guarantee that all memory will be freed. It guarantees that string length will be set to zero, but certain implementation may decide to keep part of originally allocated buffer (i.e. reserve buffer to speed up future operations, like += ).

Honestly, unless you have very small amount of available memory, I wouldn't bother. This is a very small object.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »