deleting a object by calling a method it belongs - c++

I have been learning and playing around C++ (mostly, pointers and dynamic memory allocation) for few days and I tried to create a generic class for linked list.
The classes
#include <cstdint>
#define _LINKEDLIST_DEFAULT_MAX_SIZE 2147483647L
template <typename T>
class LinkedList;
template <typename T>
class LinkedListNode;
template <typename T>
class LinkedListNode final
{
private:
LinkedListNode<T> *nextNode{nullptr};
friend LinkedList<T>;
public:
T data{};
};
template <typename T>
class LinkedList final
{
private:
LinkedListNode<T> *firstNode{nullptr};
std::int32_t maxLength{};
std::int32_t currentLength{};
public:
LinkedList(std::int32_t max_size = _LINKEDLIST_DEFAULT_MAX_SIZE)
{
maxLength = max_size;
}
void addFirst(LinkedListNode<T> *nodePtr)
{
if (firstNode == nullptr)
{
firstNode = nodePtr;
return;
}
nodePtr->nextNode = firstNode;
firstNode = nodePtr;
}
void clerList()
{
// code of releasing occupied heap memory back
}
}
Main method
int main()
{
LinkedList<short> *head{new LinkedList<short>()};
LinkedListNode<short> *node1{new LinkedListNode<short>()};
LinkedListNode<short> *node2{new LinkedListNode<short>()};
node1->data = 1;
node2->data = 2;
head->addFirst(node1);
head->addFirst(node2);
return 0;
}
And this works as properly so far as variables in my debugger shows expected results.
But my issue is how could I write my clearList() method on LinkedList<T> class? I can traverse through LinkedListNode<T> objects and release their memory back calling delete(), but calling delete(this) from clearList() to release back the memory of LinkedList<T> object at first sounds like suiciding since it tries to delete the object which it belongs to. (Note that some simple validation logics have not yet been put into the code)
Do you have any ideas to make this happen :)

Related

How to change a pointer address in a singly linked list using the "->" operator

I'm trying to write my own code for the erase function used in dynamic structures (lists specifically) of the stl library for a school project
What I had in mind was to do a loop until i found the node prior to the one i wanted to delete.
while (loop->next!= NULL){
if (loop->next==pValue){
break;
}
else {
loop->next;
}
}
prev=loop;
delete loop;
Then I want to update its pointer and instead of having it point to the node to be deleted, i want it to point to the node after the one i'm going to delete.
So can i do this?
*(prev->next)=*(pValue->next);
in case i can't, what should i do?
Here's my function erase
template <class T>
void list<T>::erase(pos pValue){
list<T>::pos prev;
list<T>::pos temp=pValue->next;
list<T>::pos loop=list<T>::first();
while (loop->next!= NULL){
if (loop->next==pValue){
break;
}
else {
loop->next;
}
}
prev=loop;
delete loop;
*(prev->next)=*(pValue->next);
delete list<T>::get(pValue);
}
And here's part of my class list
template <class T>
class list {
node<T> *pFirst;
int n;
public:
typedef node<T> *pos;
void erase(pos pValue);
};
And the structure of the node:
template <class T>
class node {
public:
T info;
node<T> *next;
};

Issue with nested templated classes

I am trying to create a simple stack using templated classes. There seems to be an issue when one class calls the constructor of the other class.
#include <iostream>
#include <vector>
int g_MaxSize = 100;
template <class T>
class Stack;
template <class D>
class Node
{
private:
D data;
public:
Node(D value): data(value)
{
}
template <class T>
friend class Stack;
};
template <class T>
class Stack
{
private:
std::vector<Node<T>> stack;
int top;
public:
Stack(): stack(g_MaxSize), top(0)
{
}
void push(T val)
{
// make sure stack isnt full
stack[top++]= Node<T>(val);
}
Node<T> pop()
{
return stack[top--];
}
Node<T> peek()
{
return stack[top];
}
};
int main() {
Node<int> testNode(1) // *this works*
Stack<int> myStack;
myStack.push(3);
return 0;
}
The error is " No matching constructor for initialization of 'Node' ". As shown in the code above, Node constructor works on its own but it does not work when done through the Stack class.
The argument of vector needs a default constructor. Node is missing one, hence the error.
Your issue here is that stack(g_MaxSize) in Stack(): stack(g_MaxSize), top(0)
is requesting that you construct g_MaxSize default constructed Nodes in the vector. You can't do that though since Node is not default constructable.
You can add a default constructor to Node that will fix that. Another way would be to pass a default Node to the vector constructor like stack(g_MaxSize, Node<T>(1)). Lastly you could create the vector with zero size and then call reserve in the constructor body to allocate the storage for the Nodes without constructing them.

C++ Templated linked list getting data element of a complex data type

I've been working on updating my old templated linked list to be able to take a complex data type. But I have no idea how to make it be able to return the data element in the node class. Currently the code for my node class looks like this:
using namespace std;
#ifndef Node_A
#define Node_A
template <class T>
class Node
{
public:
Node();
~Node();
T getData();
Node* getNext();
void setData(T);
void setNext(Node*);
private:
Node *next;
T data;
};
template <class T>
Node<T>::Node()
{
next = NULL;
return;
}
template <class T>
Node<T>::~Node()
{
return;
}
template <class T>
T Node<T>::getData()
{
return data;
}
template <class T>
Node<T>* Node<T>::getNext()
{
return next;
}
template <class T>
void Node<T>::setData(T a)
{
data = a;
return;
}
template <class T>
void Node<T>::setNext(Node* a)
{
next = a;
return;
}
#endif
Now this works perfectly fine if the data type T is a primitive but if you use a non-primitive like say a struct it would give a runtime error. I presume because structs don't do operator overloading for = operator. Is there a simple way of fixing this without completely overhauling the class?
It's not about overloading the = operator, it's about implementing the assignment operator for the struct. If you do that, you won't need to change your Node class, unless I've missed something else.
The above assumes that you'll be making copies of the data inside the Node. Alternatively, you can pass the data by reference. In this case, you need to be careful that the data doesn't get deleted before the Node object is deleted, otherwise you'll get a crash when trying to access a deleted data object from your Node.

Generic list deleting non pointers

I have a generic list with a template
template<class t>
class GenericList {
//the data is storeed in a chained list, this is not really important.
struct c_list { t data; c_list* next; ...constructor... };
public:
bool isDelete;
GenericList() : isDelete(false) {...}
void add(t d) {
c_list* tmp = new c_list(d, first->next);
//this is not really important again...
}
~GenericList() {
c_list* tmp = first;
c_list* tmp2;
while(tmp->next!=NULL) {
if (isDelete) { delete tmp->data; } //important part
tmp2=tmp->next;
delete tmp;
tmp=tmp2;
}
}
};
The important part is the isDelete
This is only a sample code
I need this because I want to store data like this:
GenericList<int> list;
list.add(22);list.add(33);
and also
GenericList<string*> list;
list.add(new string("asd")); list.add(new string("watta"));
The problem if I store only <int> the compiler said that I cannot delete non pointer variables, but I don't want to in this case. How can I solve this?
when I store <int*> there is no compiler error...
Without changing much your code, I would solve your problem as
template<class t>
class GenericList
{
//same as before
//add this function template
template<typename T>
void delete_if_pointer(T & item) {} //do nothing: item is not pointer
template<typename T>
void delete_if_pointer(T* item) { delete item; } //delete: item is pointer
~GenericList() {
c_list* tmp = first;
c_list* tmp2;
while(tmp->next!=NULL) {
delete_if_pointer(tmp->data); // call the function template
tmp2=tmp->next;
delete tmp;
tmp=tmp2;
}
}
};
EDIT: I just noticed that #ildjarn has provided similar solution. However there is one interesting difference: my solution does NOT require you to mention the type of data when calling the function template; the compiler automatically deduces it. #ildjarn's solution, however, requires you to mention the type explicitly; the compiler cannot deduce the type in his solution.
I would create a nested struct template inside your class to help:
template<typename U>
struct deleter
{
static void invoke(U const&) { }
};
template<typename U>
struct deleter<U*>
{
static void invoke(U* const ptr) { delete ptr; }
};
Then change the line that was using isDelete from
if (isDelete) { delete tmp->data; }
to
if (isDelete) { deleter<t>::invoke(tmp->data); }
delete on an int makes a program ill-formed, so the compiler will reject it, even though the delete would never be reached.
What you want is only possible if you switch from "bare" pointers to smart pointers such as unique_ptr or shared_ptr; those handle memory management for you, without explicit delete.

How to use a single Template statement for more than one function or struct?

I've been trying to represent Stacks as a template, I used a struct and every thing is good, but every time I wanted to write a template function, I had to write the same template statement, which didn't seem correct -although working-
So how can I write one template statement for all the functions?, here is my code :
template &#60typename T>
struct Stack
{
T Value;
Stack* next;
};
template &#60typename T>
void Push(T Value,Stack* &Top)
{
Stack * Cell = new Stack();
Cell->Value = Value;
Cell->next = Top;
Top = Cell;
};
template &#60typename T>
bool IsEmpty(Stack * Top)
{
return (Top==0);
}
template &#60typename T>
void Pop(T &Value,Stack* &Top)
{
if (IsEmpty(Top))
cout * Temp = Top;
Value = Top->Value;
Top = Top->next;
delete Temp;
}
}
template &#60typename T>
void GetTop(T &Value, Stack* &Top)
{
if (IsEmpty(Top))
cout Value;
}
template &#60typename T>
void EmptyStack(Stack * &Top)
{
Stack * Temp;
while (!(IsEmpty(Top)))
{
Temp = Top;
Top = Top->next;
delete Temp;
}
}
Hope what I mean is clear now, sorry for the slight question :(
thanks in advance.
If (as appears to be the case based on your comment) you want them as free functions, you can't. You'll also have to change the Stack parameter, something like this:
template <typename T>
void Push(T Value, Stack<T>* &Top)
{
Stack * Cell = new Stack();
Cell->Value = Value;
Cell->next = Top;
Top = Cell;
};
As it stands, I'm not too excited about your design though. You try to use the Stack type as both an actual stack, and as a single node (Cell) in the stack. This is unnecessarily confusing at best.
Edit: As far as stack vs. node goes, what I'm talking about is (as in the code immediately above): Stack *Cell = new Stack(); -- you're allocating a single Cell that goes in the stack, but the type you're using for it is Stack.
I'd do something like this instead:
template <class T>
struct Stack {
struct node {
T data;
node *next;
};
node *head;
};
template <class T>
void push(T item, Stack<T> *&s) {
Stack<T>::node *n = new Stack<T>:node();
n->data = item;
n->next = s->head;
s->head = n;
}
It doesn't make a lot of difference in what you're really doing, but when you're putting something onto a stack, allocating a Stack<T>::node seems (at least to me) to make a lot more sense than allocating a Stack<T>. A stack containing multiple nodes makes sense -- a Stack containing multiple stacks really doesn't.
You could simply write a template class instead, and write all those functions as methods of that class. They will then share the same template parameters as the class.