How to delete a local dynamic object in a function?

I have declared a dynamic object in a local class function. The problem is I am using new to declare the object, which means I have to use delete to release the memory. I can't use the destructor because its a local object, so what else can I do.

I looked around and a viable solution would be using a unique_ptr, but I am not 100% sure. What should I do in a situation like this? Thanks in advance.

1
2
3
4
5
6
7
 void LinkedList::addNode(int nValue)
{
	Node * newNode = new Node;
	newNode->data = nValue;

    // some more code here
}
what do you actually do with your newNode object? Presumably you're adding it to your list at the end of that function? So when you're LinkedList object dies you'll need to free up your memory there? Or, like you suggest use a std::unique_ptr.

I wouldn't class it as a 'local variable' though.
The idea is to make newNode point to whatever node the head pointer is pointing to. So that whenever the addNode(int nValue) is called, a new node is produced and points to what the head pointer is pointing to, and then the head pointer points to the newly produced node.

1
2
3
4
5
6
7
8
9
void LinkedList::addNode(int nValue)
{
	Node * newNode = new Node;
	newNode->data = nValue;
	
	newNode->next = m_head;    // <- The head pointer is a class member variable
	
	m_head->next = newNode;
}
Last edited on
and then the head point points to the newly produced node

so why do you want to destroy it?
I don't want to destroy the node immediately after its produced, only after I have finished with the nodes. I would have to eventually delete the newNode right? to prevent a memory leak.
You would indeed, but not until your LinkedList object goes out of scope I guess?
Topic archived. No new replies allowed.