I need to destroy a string in C ++

if I have a line in the class then memory is allocated. Should I destroy the string in the destructor? eg.

  class A {
   string Test;
   A () {
     Test = "hello world";
   }

   A (string & name) {
     Test = name;
   }

   ~ A () {
     // do I have to destroy the string here?
   }
 }

I am an old c / C ++ programmer (pre stl) and am returning to C ++. Is the string automatically destroyed using the magic of the pattern?

TIA, Dave

+6
source share
4 answers

Yes, std :: string resources are cleared automatically. Standard strings and containers allocate / free for you. HOWEVER, a container of pointers does not release what these pointers point to. You have to go through them yourself.

+8
source

No. The string destructor is invoked as soon as instance A goes out of scope.

+3
source

You are not creating a pointer to a string, so Test will be pushed onto the stack (assuming that object A has been pushed onto the stack). Thus, when he leaves the area of ​​effect, he will be automatically released. If Test was a pointer, it will be allocated on the heap, and you will need to delete it in the destructor

+3
source

You clear your clutter, and the standard library clears your clutter. The memory that std :: string allocates is a mess.

The default behavior of a destructor is to call destructors for each database and data item. Your string is a data member, so its destructor is called. Its destructor does everything that needs to be done here, so it is no longer necessary (and it would actually be very wrong) to clear anything here than if you had a line as a local variable in main ().

0
source

All Articles