Removing a string object in C ++

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

string str; 

I copied some data into it and did some operations. Now I want to delete the str object from memory. I cannot use the delete operator, since str is not a pointer. How to delete this object from memory in order to return the memory allocated to it?

Thanks, Rakesh.

+4
source share
4 answers

You don’t have to. When a line goes out of scope, its destructor will be called automatically and memory will be freed.

If you want to clear the line right now (without waiting to exit the area), just use str.clear() .

+8
source
 str.clear(); 

or

 str = ""; 

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

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

However, implementations that use a little string optimization will save several bytes of stack space (and str itself, of course, also lives on the stack).

In the end, I agree with all the comments saying that it is doubtful why you want to do this. Ass in the near future, when str goes out of scope, its data will be automatically deleted:

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

Add additional area

 { String str; ... ... } 

to make sure str goes beyond when you no longer need it. Recall that this can be difficult in terms of defining other variables.

+2
source

Now I want to delete the str object from memory.

You can not. At least you cannot delete it completely. str is already allocated on the stack (or in the code segment, if it is a global variable), and it will not completely disappear until you return from the subprogram, leave the area in which it was created (or until you exit the program - for the global variable).

You can call .clear () or assign it an empty string, but this does not guarantee the release of all memory. It ensures that the string length is set to zero, but a certain implementation may decide to keep part of the buffer originally allocated (i.e., a backup buffer to speed up future operations, for example, + =).

Honestly, if you have little available memory, I would not bother. This is a very small object.

+1
source

Source: https://habr.com/ru/post/1314046/


All Articles