A quick question on strings and destructors.

If I have a class such as
class MyClass{
[..]
string myString;
[..]
};

do I need to delete myString in my destructor? I tried to experiment with this but I get an error when I try to include the line
delete myString;
in my class's destructor. The error i get is:
"[...]: error C2440: 'delete' : cannot convert from 'std::string' to 'void *'

I thought strings from <string> were dynamic objects so I have to clean up after them? Do I need to worry about this?
You only need to delete manually allocated pointers; i.e. Exactly one delete for each new.

On a side note, although string is dynamic, the deletion of any used pointers is done internally in its own destructor. Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class DynamicArray {
   //private members
   int *array;
   int count; //number of elements assigned
   int capacity; //total number of elements that the array can hold

 public:
   DynamicArray(int initCap = 10);
   ~DynamicArray() { delete[] array; } //clean up is hidden from the user

   void add(int ele, int index);
   void add(int ele) { add(ele, count); }
   int size() { return count; }
   //...
};

DynamicArray::DynamicArray(int initCap) {
   capacity = initCap >= 0 ? initCap : 0;
   count = 0;
   array = new int[capacity]; //note: a call to "new" in the constructor
}

void DynamicArray::add(int ele, int index) {
   //assert( count <= capacity );
   if( count >= capacity ) {
    //we need more room
      newCap = 2 * capacity + 1; //or some other increase size function
      int *newArr = new int[newCap];
      //copy values in "array" to "newArr" from 0 to "capacity"
      delete[] array; //clean up old memory
      capacity = newCap;
      array = newArr;
   }
   //now add the element...
   ++count;
}

int main() {
   DynamicArray arr;
   arr.add(5);
   arr.add(10);
   arr.add(-3);
   //we don't need to delete the DynamicArray because when it leaves scope it's destructor is called
   return 0;
}
Last edited on
closed account (zb0S216C)
myString doesn't allocate any memory, therefore, you don't need to delete it. You only use delete on allocated memory; otherwise, you're looking for trouble.

You can read up on new[1] and delete[1] in the references section below.

References:
[1]http://www.cplusplus.com/reference/std/new/operator%20new%5B%5D/
[1]http://www.cplusplus.com/reference/std/new/operator%20delete[]/

Wazzak
No you shouldn't. string Mystring is not a pointer So you can't use delete operator to clean it up. If you want to do this just assign MyString='\0';
Topic archived. No new replies allowed.