I was reading a post somewhere on this site about making a type-dynamic list and came up with this. The issue is I'm thinking it's leaking memory when the list grows. Finally, are there any ways to improve this code?
#include <iostream>
using namespace std;
class DynamicType {
public:
union {
int integer;
char* string;
};
enum {
is_int,
is_string
} what_type;
};
class DynamicTypeList {
DynamicType* data;
DynamicType* data_begin;
DynamicType* data_end;
int len;
int actual_len;
int increment;
void expand() {
int oldlen = actual_len;
actual_len += increment;
DynamicType* temp = new DynamicType[actual_len];
data = data_begin;
for (int i = 0; i < oldlen; i++) {
temp->what_type = data->what_type;
if (temp->what_type == temp->is_int)
temp->integer = data->integer;
else if (temp->what_type == temp->is_string)
temp->string = data->string;
temp++;
data++;
}
//delete data;
data = temp;
}
public:
DynamicTypeList() {
len = 0;
increment = 10;
actual_len = increment;
data = new DynamicType[increment];
}
void add(int i) {
if (len == actual_len) expand();
len++;
data->what_type = data->is_int;
data->integer = i;
data_end = data;
if (len == 1) data_begin = data;
data++;
}
void add(char* sz) {
if (len == actual_len) expand();
len++;
data->what_type = data->is_string;
data->string = sz;
data_end = data;
if (len == 1) data_begin = data;
data++;
}
DynamicType* begin() const {
return data_begin;
}
DynamicType* end() const {
return data_end + 1;
}
};
int main (int argc, char** argv) {
DynamicTypeList list;
list.add(42);
list.add("forty-two");
list.add(44);
list.add("forty-four");
for (DynamicType* item = list.begin(); item != list.end(); item++) {
if (item->what_type == item->is_int) {
cout << item->integer << endl;
} else if (item->what_type == item->is_string) {
cout << item->string << endl;
}
}
return 0;
}