I have a class List
which allocates memory automatically to store a list of items.
It has a destructor which deallocates this memory:
List::~List()
{
free(memory);
}
This means, if I create a new
list, I can use delete
to call the destructor and free the memory.
The destructor will also be called once the variable is out of scope which is ALMOST always what I want. e.g:
int func()
{
List list;
list.push(...);
...
return 47;
}
However, what if I want to return that list?
List func()
{
List list;
return list;
}
I am alright with the list being copied because it's returned by value, and doesn't have much data to copy (only a few ints, and a pointer).
However, the memory that the list allocated and has a pointer to, contains a LOT of data.
Since I am returning the list, the list is being copied along with the pointer to this data.
Since the list is now out of scope, the destructor is called, which frees up the pointer to that data, even though the copy also has the pointer.
How do I prevent this destructor from being called?
1) There is probably a solution by creating a copy constructor, however, I don't want to do this because then all the data at that pointer will likely have to be copied which is a waste of time and temporarily requires double the memory to be allocated.
2) I know I could just create a pointer List* list
and return that, but I want to avoid the necessity of allocating new memory for that list if possible, and also want to avoid wasting more memory for a pointer (8 bytes or something).
Thanks in advance,
David.