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?
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 = newint[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 = newint[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;
}
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.