wandering-warrior wandering-warrior - 1 year ago 72
C++ Question

Class Design Problems (managing memory allocation & deallocation)

1) So i have made a somewhat modified form of linked list that has indexed based addressing and other delete functions. I am just gonna copy the header file i made...

template<class T>
class LinkedList
int del_node(); // deletes the Node and element
int remove_node(); // deletes the Node only
int get_length();
int search_node(T*); // matches the pointer to see if its the same element
void add(T*);
void clear_list(); // calls deletes on all nodes and all elements
bool is_blank();
T& get_at(int); // operates like a vector get_at
struct Node
T* element; // pointer passed to add(T*) is stored here.
Node* next;

Now see how i am adding an object in a linked list. I need to pass in an object pointer which i am passing in the form of

new Object()

This is particularly useful when i am adding Vertices of a graph. I just input the data and other fields from the user and call

LinkedList graph
graph.add(new Vertex(arguments));

Now there comes a situation when i have to copy some elements from the
for temporary storage. Now i want to be able to remove elements from
after any kind of operation. But if i use
it destroys the internal Node and deletes the object pointed by the pointer
i passed to it. So i created an additional function
that only deletes the Node but not the object pointed by the

So i wanted to ask if its okay to do this or is there a design fault in my list and i should not be doing this? I am thinking of this from a library point of view for example if i would go about providing this class in a library. Is this suitable or will this confuse people? Any advice would be appreciated.

Please, I don't need any suggestions to use a replacement
function/class/library like vector. I am studying Data Structures and i have
to design any sort of data structure myself.

Answer Source

The more idiomatic fashion is to have Node::~Node always call delete element;, but add a T* Node::release();. This is what std::unique_ptr does for instance.

The implementation is straight forward:

T* Node::release()
  T* tmp = element;
  element = nullptr;
  return tmp;

That way the Node d'tor is still correct, but you can "save" the data from deletion.

This is also the first step in addressing what I sense is a flaw in your implementation. You implement all functionality in LinkedList, even that which is relevant to the behavior of the internal class Node. Don't do that. Give Node a role and an interface related to that role. Than have LinkedList work by using that interface.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download