So I am trying to make a linked list that can contain any data type at the same time. The list contains Element objects:
struct Element {
void* data;
Element* next;
Element(const void* content, Element* next_ele) {
next = next_ele;
data = new void; // this doesn't work
(*data) = (*content)
}
};
The reason I have to allocate memory for data
is because if I just assign data = content
, if *content
is destroyed (such as when leaving a local function), *data
will also be destroyed. That means if I add some elements to the list inside a function, those elements will disappear from the list when the function exits. The example is below:
// in List.cpp
List::add(void *content) {
// for this question, ignore the case when list is empty
Element *ele = new Element(content, nullptr);
last.next = ele
last = ele
}
// main.cpp
List myList;
void addEle() {
int a; double b; char c;
myList.add(&a); myList.add(&b); myList.add(&c);
}
int main()
{
myList = newList();
addEle();
}
When addEle() exits, variables a, b, c
doesn't exist anymore. So the content of the list is nonsense.
So how can I allocate memory of void type in C++ to solve this problem? If I can't, is there any solution (except template) so that when I leave a local function, the content of a list isn't changed ?
Thank you for your help.
Edit 1: I can't use template because using template means each list object can only contain 1 data type. But I want to do something like myList.add(1), myList.add(3.5), myList.add('c'), myList.add(student), etc