Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do I need to destroy a string in c++

Tags:

c++

stl

if I have a string in a class, then memory is allocated. Do I have to destroy the string in the destructor? e.g.

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

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

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

I'm an old c/c++ (pre stl) programmer and getting back into c++. Is the string destroyed automatically using some template magic?

tia, Dave

like image 645
daven11 Avatar asked Dec 04 '10 01:12

daven11


People also ask

How do you empty a string in C?

If you want to zero the entire contents of the string, you can do it this way: memset(buffer,0,strlen(buffer)); but this will only work for zeroing up to the first NULL character. To clarify, the last method will work if buffer is is an array, but not if it is a pointer.

Does STD string have a destructor?

Return c_str of local std::stringWhen the std::string goes out of scope, its destructor is called and the memory is deallocated, so it is no longer safe to use the pointer.

Does C++ string class needs a destructor?

A class needs a destructor if it acquires a resource, and to manage the resource safely it probably has to implement a copy constructor and a copy assignment. If these special functions are not defined by the user, they are implicitly defined by the compiler.


1 Answers

Yes, std::string's resources are cleaned up automatically. Standard strings and containers allocate/deallocate for you. HOWEVER, a container of pointers doesn't free up what those pointers point to. You have to loop through those yourself.

like image 176
Mark Storer Avatar answered Sep 27 '22 20:09

Mark Storer